Create Word Document with Java - java

I have default table model fetch with data from database and i want to print in doc word as a table. How to achieve that. See the code below:
try {
try {
con = connCC.getDBconnection();
} catch (ClassNotFoundException ex) {
Logger.getLogger(CustomerSR.class.getName()).log(Level.SEVERE, null, ex);
}
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select * From Appointment");
while (rs.next()) {
for (int col = 0; col < 1; col++) {
rowData.add(rs.getString(1));
rowData.add(rs.getString(2));
rowData.add(rs.getString(3));
rowData.add(rs.getString(4));
rowData.add(rs.getString(5));
}
model.addRow(rowData);
}
window.display(model);
//window.display(names, phones, addresses);
} catch (SQLException ex) {
ex.printStackTrace();
}
}

In the above comments, I see that you are already using Apache POI. If I understand correctly, you want to input data from a database into a table on a word document. Take a look at this tutorial on creating tables in word with Apache POI:
http://www.tutorialspoint.com/apache_poi_word/apache_poi_word_tables.htm
You can set the text directly with the data that you retrieve from the database. I can post an example if you need it, but the tutorial does a pretty good job of showing what you need to do.
----UPDATE----
Sorry that it took me a while, went to lunch with the wife. Try this:
// Blank Document
XWPFDocument document = new XWPFDocument();
// Write the Document in file system
FileOutputStream out = new FileOutputStream(new File("create_table.docx"));
// Create table
XWPFTable table = document.createTable();
// Table row
XWPFTableRow tableRow;
int rowCount = model.getRowCount() - 1;
int colCount = model.getColumnCount() - 1;
// Iterate through rows
for (int row = 0; row <= rowCount; row++) {
tableRow = table.getRow(row);
// Iterate through columns
for (int col = 0; col <= colCount; col++) {
tableRow.getCell(col).setText((String) model.getValueAt(row, col));
// If more columns, add cell
if (row == 0 && col < colCount) {
tableRow.addNewTableCell();
}
}
// If more rows, add row
if (row < rowCount) {
table.createRow();
}
}
// Write to word document and close file.
document.write(out);
out.close();

Related

POI XSSF overwriting specific cells in excel file

I am trying to write out to an existing excel file. I don't want to create new rows or cells, I just want to write out the value from my array into the value at row x column y. Every time I have tried this so far I can only get it to work if I create a new row. Please help!!!
Integer columns = DataImport.columns_in_sheet[0];
Integer rowNum = learnerRow + 2;
try {
FileInputStream inp = new FileInputStream("D:/location/update.xlsx");
XSSFWorkbook wb = null;
wb = (XSSFWorkbook) WorkbookFactory.create(inp);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row = sheet.getRow(18);//places the start row
XSSFCell cell = null;//places the start column
cell = row.getCell(0);
//#########################################################################################
//#########################################################################################
for (int j = 0; j < exportData.length; j++) {
//sheet.createRow(rowNum+j);
//row = sheet.getRow(rowNum+j);
//row = sheet.getRow(rowNum+j);
for (int i=0; i < columns;i++){
cell.setCellType(CellType.STRING);
cell.setCellValue(exportData[j][i]);
}
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("D:/location/update.xlsx");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
this code throws a null pointer because of row being null, I can only seem to get rid of the error by creating new rows. I am using XSSF formatting.
The logic of your code snippet is not clear. It looks not logically to me.
But to avoid NPE while using rows and cells from present sheets, one always needs check whether the row or cell was present already or needs to be new created. This is necessary because for not present rows Sheet.getRow will return null. Also Row.getCell will return null for not present cells.
So we can do:
Sheet sheet = ...
Row row = sheet.getRow(rowIdx); if (row == null) row = sheet.createRow(rowIdx);
Cell cell = row.getCell(cellIdx); if (cell == null) cell = row.createCell(cellIdx);
Now row either is a row which was already present or it is a new created row. And cell either is a cell which was already present or it is a new created cell. Neither row nor cell will be null. And at first present rows/cells will be got before they were new created if not present. So present rows and cells will not be destroyed.
The same is needed in loops:
Sheet sheet = ...
Row row;
Cell cell;
for (int rowIdx = 0; rowIdx < 10; rowIdx++) {
row = sheet.getRow(rowIdx); if (row == null) row = sheet.createRow(rowIdx);
for (int cellIdx = 0; cellIdx < 10; cellIdx++) {
cell = row.getCell(cellIdx); if (cell == null) cell = row.createCell(cellIdx);
// do something with cell
}
}

Apache Poi - createCell() Method doesn't accept index via for loop as parameter

I want to create an Excel file with Apache Poi, based on the sheet of another Excel file. Only the first two columns and their corresponding rows should be applied to the new Excel sheet.
First, I insert all cells of the first column, then I increment the columnIndex to insert the other cells.
private static void createNewWorkBook(XSSFSheet oldSheet) {
XSSFWorkbook newWorkbook = new XSSFWorkbook();
XSSFSheet newSheet = newWorkbook.createSheet("test-sheet");
for (int columnIndex = 0; columnIndex < 2; columnIndex++) {
int rowIndex = 0;
for (Row oldRow : oldSheet) {
XSSFRow newRow = newSheet.createRow(rowIndex);
XSSFCell newCell = newRow.createCell(columnIndex);
newCell.setCellValue("Hello"); // just for test purposes
// newCell.setCellValue(oldSheet.getRow(rowIndex).getCell(columnIndex).getStringCellValue());
rowIndex++;
}
}
try {
FileOutputStream fos = new FileOutputStream(new File("CreateExcelDemo.xlsx"));
newWorkbook.write(fos);
fos.close();
} catch (
IOException e) {
e.printStackTrace();
}
}
Unfortunatley it doesn't work. I only get the values of the second column in my newly generated excel-sheet. The first column is just empty.
BUT:
If I replace the columnIndex with 0 or 1, it works! Where is my thinking problem?

Data not showing when using PdfPTable in Itext Report

I am building an itext report with nested PdfPTables. I have been able to verify that the data is getting from the database to my data objects, but I have not been able to get that data to show up in the body of the report. The Header, which I had directly copied from a previous (functioning) report is able to add the rows, but all I get for my trouble in the body is a single line (not a single line of data, a single line as if drawn on the report itself).
I am hopeful that I am merely forgetting something simple in the middle. I will show a few of my methods:
public void makePDF(String jsonData, Document document, PdfWriter writer)
{
this.beginNewLandscapePage(document, writer);
try
{
jsonData = DBConnect.PrintReport(CommonConstants.reportAPI,this.getParams());
JSONObject json = (JSONObject) getParser().parse(jsonData);
//System.out.println("json = "+json);
JSONObject reportHeaderObject = (JSONObject) (json.get(CommonConstants.reportHeaderObjectField));
JSONObject reportPayloadObject = (JSONObject) (json.get(CommonConstants.reportPayloadObjectField));
JSONArray reportData = (JSONArray) (reportPayloadObject.get(CommonConstants.reportDataArrayField));
JSONObject reportTotals = (JSONObject) (reportPayloadObject.get(CommonConstants.reportTotalsObjectField));
PdfPTable mainTable = new PdfPTable(1);
mainTable.setWidthPercentage(100);
mainTable.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
this.buildHeader(reportHeaderObject,writer);
boolean showSubTotalLabel;
try
{
showSubTotalLabel = this.getIsSubTotaled();
}//try
catch (NullPointerException ne)
{
showSubTotalLabel = false;
}//catch (NullPointerException)
String sortStub = null;
if(showSubTotalLabel)
{
sortStub = Utils.getJSONAsString(reportPayloadObject, CommonConstants.sortStubField);
}//if(showSubTotalLabel)
for (int i = 0; i < reportData.size(); i++)
{
JSONObject row = (JSONObject) reportData.get(i);
mainTable.addCell(this.buildRow(row,showSubTotalLabel,sortStub,false));
}//for (int i = 0; i < dedInfo.size(); i++)
mainTable.addCell(this.buildRow(reportTotals,showSubTotalLabel,sortStub,true));
document.add(mainTable);
}//try
catch (ParseException e)
{
e.printStackTrace();
}//catch (ParseException)
catch (DocumentException e)
{
e.printStackTrace();
}//catch (DocumentException)
}//makePDF(String, Document, PdfWriter)
public PdfPCell buildRow(JSONObject row,boolean showSubTotalLabel,String sortStub,boolean isGrandTotal)
{
PdfPTable innerRowTable = new PdfPTable(this.getInnerRowTableWidths());
PdfPTable outerRowTable = new PdfPTable(this.getOuterRowTableWidths());
PdfPTable resultTable = new PdfPTable(1);
PdfPTable dedColumn;
PdfPTable leftColumn;
PdfPTable payColumn;
PdfPTable rightColumn;
PdfPTable taxColumn;
PdfPCell result;
PayrollRegisterData rowData2;
int numRows = 5; //Number of rows in the right column, minus the two matched by the totals row and header row
if(showSubTotalLabel)
{
resultTable.addCell(this.addSubTotalHeader(row,sortStub));
}//if(showSubTotalLabel)
boolean isTotal = true;
try
{
JSONObject totalObject = (JSONObject)row.get(CommonConstants.totalsObjectField); //test only to force the NullPointerException
}//try
catch(NullPointerException npe)
{
isTotal = false;
}//catch(NullPointerException)
if (isTotal)
{
PayrollRegisterVoucherData rowData = new PayrollRegisterVoucherData(row);
showSubTotalLabel = false;
rowData2 = rowData;
leftColumn = this.buildLeftColumnVoucher(rowData);
rightColumn = this.buildRightColumnVoucher(rowData);
}//if (isTotal)
else
{
PayrollRegisterTotalData rowData = new PayrollRegisterTotalData(row);
numRows = 4; //Number of Rows in the left column of the totals minus the two for the totals and header
showSubTotalLabel = true;
rowData2 = rowData;
leftColumn = this.buildLeftColumnTotal(rowData);
rightColumn = this.buildRightColumnTotal(rowData);
if(isGrandTotal)
{
resultTable.addCell(this.addTotalHeader(CommonConstants.reportTotalLabel));
}//if(isGrandTotal)
else
{
resultTable.addCell(this.addTotalHeader(row,sortStub));
}//else
}//else
if (rowData2.getDeductionData().length > numRows)
{
numRows = rowData2.getDeductionData().length;
}//if (rowData.getDeductionData().length > numRows)
if (rowData2.getPayData().length > numRows)
{
numRows = rowData2.getPayData().length;
}//if (rowData.getPayData().length > numRows)
if (rowData2.getTaxData().length > numRows)
{
numRows = rowData2.getTaxData().length;
}//if (rowData.getTaxData().length > numRows)
dedColumn = this.buildDedColumn(rowData2,numRows);
payColumn = this.buildPayColumn(rowData2,numRows);
taxColumn = this.buildTaxColumn(rowData2,numRows);
innerRowTable.addCell(Utils.getBlankCell());
innerRowTable.addCell(payColumn);
innerRowTable.addCell(Utils.getBlankCell());
innerRowTable.addCell(taxColumn);
innerRowTable.addCell(Utils.getBlankCell());
innerRowTable.addCell(dedColumn);
innerRowTable.addCell(Utils.getBlankCell());
outerRowTable.addCell(leftColumn);
outerRowTable.addCell(innerRowTable);
outerRowTable.addCell(rightColumn);
resultTable.addCell(outerRowTable);
result = new PdfPCell(resultTable);
return result;
}//buildRow(JSONObject,boolean,String,boolean)
I know I am a bit rusty with this, but the data is getting into the data objects successfully, and it is running without errors. It just doesn't show any data in the data section of the report. Is my problem with my mainTable, my buildRow, or do those look right and I need to look deeper into my code?
It turns out that the issue was not posted in the original code snippet, at least not completely. The issue was that the float[] variables I had set in the constructor were reversed for the inner and outer tables. Thus, the outer table, which I thought only wanted three columns per row, was expecting 7 columns. So, when I added it to the resultTable, it was not adding anything at all.

POI HSSF not iterating full set of rows

Cannot iterate the full extent of rows in my XLS spreadsheet. The code {sheet.getPhysicalNumberOfRows} returns 33492 without raising exception, but there are about 43,000 rows??.
If I supply the right number manually the loop executes without complaint.
It must be simple answer but I cannot find one anywhere. can somebody help?
try {
POIFSFileSystem fs = new POIFSFileSystem(new
FileInputStream(fileLocation));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows(); //Gets => 33494
int cols = 1; // No of columns
int tmp = 0;
for (int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if (row != null) {
cell = row.getCell(0);
if (cell != null) {
System.out.println("Line number: " + r " = " + cell);
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}

Creating multiple sheets using Apache poi and servlets

When i am creating multiple sheets using Apache poi and servlets. It is creating the sheet but not writing the data to file. I am trying to write the first 1000 records to sheet1 and next 1000 to sheet2 through below code, but not working
private void writeDataToExcelFile(String string,
ArrayList<ArrayList<String>> excelData, OutputStream outputStream) {
HSSFWorkbook myWorkBook = new HSSFWorkbook();
String sheetName = "";
sheetName = "Document-" + 0;
HSSFSheet mySheet = myWorkBook.createSheet();
HSSFRow myRow = null;
HSSFCell myCell = null;
for (int rowNum = 0; rowNum < excelData.size(); rowNum++) {
ArrayList<String> rowData = excelData.get(rowNum);
if(rowNum>0 && rowNum%1000 == 0)
{
sheetName = "Document-" + (rowNum/1000);
mySheet = myWorkBook.createSheet();
}
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < rowData.size(); cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(rowData.get(cellNum));
}
}
System.out.println("Last row:" + mySheet.getLastRowNum());
System.out.println("Row number:" + mySheet.rowIterator().next().getRowNum());
try {
myWorkBook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What is wrong with my logic.Please do the needful help.
Thanks
When you loop through the dataset, you are wanting to split at row 1000 to start a new sheet, which is fine, however when you start the new sheet, the next row you create is row 1001 (the outer loop index variable)
myRow = mySheet.createRow(rowNum);
To get the effect you wish, change the loop to be something like this:
int currentRow = 0;
for (int rowNum = 0; rowNum < excelData.size(); rowNum++)
{
ArrayList<String> rowData = excelData.get(rowNum);
if(currentRow == 1000)
{
sheetName = "Document-" + (rowNum/1000);
mySheet = myWorkBook.createSheet();
currentRow = 0;
}
myRow = mySheet.createRow(currentRow);
for (int cellNum = 0; cellNum < rowData.size(); cellNum++)
{
myCell = myRow.createCell(cellNum);
myCell.setCellValue(rowData.get(cellNum));
}
currentRow++;
}
I haven't compiled this, so I don't know if it'll work right away, but it should point you in the right direction.
HTH
Edit
Thinking about this further, you could get the same effect from making a 1 line change to the original application (albeit losing a little bit of clarity):
myRow = mySheet.createRow(rowNum%1000);

Categories

Resources