ResultSet to Excel (*.xlsx) Table Using Apache POI - java

I am trying to write ResultSet to Excel (*.xlsx) Table using Apache Poi.
Invalid Table Object Error in Office Excel
However, even though it writes the Excel file without any error, when I try to open it in Office Excel 2013, it shows an error and removes the table object to give only plain data view.
Here is the rough Sample Code using this example:
public static void writeExcel(ResultSet rs, int sqliteRowCount, String dir) {
System.out.println("Writing Excel(*.xlsx) File...");
XSSFWorkbook workbook = null;
try {
if (rs != null) {
// Get ResultSet MetaData
ResultSetMetaData rsmd = rs.getMetaData();
// Number of columns
int numColumns = rsmd.getColumnCount();
// Number of rows
// + 1 for headers
int numRows = sqliteRowCount + 1;
workbook = new XSSFWorkbook();
// Create Excel Table
XSSFSheet sheet = workbook.createSheet("Text");
XSSFTable table = sheet.createTable();
table.setDisplayName("Test");
CTTable cttable;
cttable = table.getCTTable();
// Style configurations
CTTableStyleInfo style = cttable.addNewTableStyleInfo();
style.setName("TableStyleMedium16");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
// Set Table Span Area
AreaReference reference = new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1));
cttable.setRef(reference.formatAsString());
cttable.setId(1);
cttable.setName("Test");
cttable.setDisplayName("Test");
cttable.setTotalsRowCount(numRows);
cttable.setTotalsRowShown(false);
// Create Columns
CTTableColumns columns = cttable.addNewTableColumns();
columns.setCount(numColumns);
// Create Column, Row, Cell Objects
CTTableColumn column;
XSSFRow row;
// Add Header and Columns
XSSFRow headerRow = sheet.createRow(0);
for (int i = 0; i < numColumns; i++) {
column = columns.addNewTableColumn();
column.setName("Column" + (i + 1));
column.setId(i + 1);
headerRow.createCell(i).setCellValue(rsmd.getColumnLabel(i + 1));
}
// Write each row from ResultSet
int rowNumber = 1;
while (rs.next()) {
row = sheet.createRow(rowNumber);
for (int y = 0; y < numColumns; y++) {
row.createCell(y).setCellValue(rs.getString(y + 1));
}
rowNumber++;
}
// Set AutoFilter
CTAutoFilter fltr = CTAutoFilter.Factory.newInstance();
fltr.setRef((new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1))).formatAsString());
cttable.setAutoFilter(fltr);
// sheet.setAutoFilter(CellRangeAddress.valueOf((new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1))).formatAsString()));
// Freeze Pan
sheet.createFreezePane(0, 1, 0, 2);
}
} catch (SQLException ex) {
System.out.println("SQL Error while writing Excel file!");
} finally {
try {
// Let's write the excel file now
if (workbook != null) {
String excelDir = dir + File.separator + "workbook.xlsx";
try (final FileOutputStream out = new FileOutputStream(excelDir)) {
workbook.write(out);
}
}
} catch (IOException ex) {
System.out.println("IO Error while writing Excel summary file!");
}
}
}
I know something is wrong with my code, but can't figure it out.
Any idea, why this is happening, where would be potential mistake in my code.
Update 1:
Table XML file in Excel archive if created using Apache POI
<?xml version="1.0" encoding="UTF-8"?>
<table displayName="Test" ref="A1:B881" id="1" name="Test" totalsRowCount="881" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" totalsRowShown="0"><autoFilter ref="A1:B881"/><tableColumns count="2"><tableColumn name="ID" id="1"/><tableColumn name="Name" id="2"/><tableStyleInfo name="TableStyleMedium2" showColumnStripes="true" showRowStripes="true"/></table>
Table XML file in Excel archive if table created manually
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="1" name="Table1" displayName="Table1" ref="A1:B881" totalsRowShown="0"><autoFilter ref="A1:B881"/><tableColumns count="2"><tableColumn id="1" name="ID"/><tableColumn id="2" name="Name"/></tableColumns><tableStyleInfo name="TableStyleLight9" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/></table>
In addition, if I open the Excel archive, it does not have a theme folder in the one created by Apache POI but it is present in the one create manually in Office Excel. Strange.
Update 2:
Sample executable code (Using Netbeans):
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package apachepoi_exceltest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumns;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo;
/**
*
*/
public class ApachePOI_ExcelTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String outputDir = "Your Local Directory Here";
// TODO code application logic here
HashMap<String, String> dataMap = new HashMap<>();
dataMap.put("ID 1", "Dummy Name 1");
dataMap.put("ID 2", "Dummy Name 2");
dataMap.put("ID 3", "Dummy Name 3");
dataMap.put("ID 4", "Dummy Name 4");
writeExcel(dataMap, outputDir);
}
private static void writeExcel(HashMap<String, String> dataMap, String outputDir) {
System.out.println("Writing Excel(*.xlsx) Summary File...");
XSSFWorkbook workbook = null;
try {
// Number of columns
int numColumns = 2; // ID and Name
// Number of rows
int numRows = dataMap.size() + 1; // +1 for header
// Create Workbook
workbook = new XSSFWorkbook();
// Create Excel Table
XSSFSheet sheet = workbook.createSheet("Summary");
XSSFTable table = sheet.createTable();
table.setDisplayName("Test");
CTTable cttable;
cttable = table.getCTTable();
// Style configurations
CTTableStyleInfo style = cttable.addNewTableStyleInfo();
style.setName("TableStyleMedium16");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
// Set Tabel Span Area
AreaReference reference = new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1));
cttable.setRef(reference.formatAsString());
cttable.setId(1);
cttable.setName("Test");
cttable.setDisplayName("Test");
cttable.setTotalsRowCount(numRows);
cttable.setTotalsRowShown(false);
// Create Columns
CTTableColumns columns = cttable.addNewTableColumns();
columns.setCount(numColumns);
// Create Column, Row, Cell Objects
CTTableColumn column;
XSSFRow row;
// Add ID Header
column = columns.addNewTableColumn();
column.setName("Column" + (1));
column.setId(1);
// Add Name Header
column = columns.addNewTableColumn();
column.setName("Column" + (1));
column.setId(1);
// Add Header Row
XSSFRow headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue("Name");
int rowNumber = 1;
for (Map.Entry<String, String> entry : dataMap.entrySet()) {
String id = entry.getKey();
String name = entry.getValue();
row = sheet.createRow(rowNumber);
row.createCell(0).setCellValue(id);
row.createCell(1).setCellValue(name);
rowNumber++;
}
// Set Filter (Below three lines code somehow not working in this example, so setting AutoFilter to WorkSheet)
// CTAutoFilter fltr = CTAutoFilter.Factory.newInstance();
// fltr.setRef((new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1))).formatAsString());
// cttable.setAutoFilter(fltr);
sheet.setAutoFilter(CellRangeAddress.valueOf((new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1))).formatAsString()));
// Freeze First Row as header Row
sheet.createFreezePane(0, 1, 0, 2);
} catch (Exception ex) {
System.out.println("Error while writing Excel summary file!");
} finally {
try {
// Lets write the Excel File Now
if (workbook != null) {
String excelDir = outputDir + File.separator + "workbook.xlsx";
try (final FileOutputStream out = new FileOutputStream(excelDir)) {
workbook.write(out);
}
}
} catch (IOException ex) {
System.out.println("IO Error while writing Excel summary file!");
}
}
}
}
Libraries Used:
ooxml-schemas-1.1.jar
poi-3.11-beta2-20140822.jar
poi-ooxml-3.11-beta2-20140822.jar
xmlbeans-2.6.0.jar

What's wrong with your code is a presence of a single line.
"cttable.setTotalsRowCount(numRows);"
Remove it and everything will work.
If in doubt, compare the XML definitions of some working table created manually in Excel and the definitions created with Apache POI

I had the same issue.
Digging deeply, I found that for some table XML data in the XLSX package, Excel is changing a single > to > after performing the repair. The XML from POI makes sense (use < and > to surround XML elements) so I have no idea why Microsoft chooses to break it.
If its the same case for you, I'd not worry too much about it.
If you want to see if you have this particular difference:
Create XLSX with POI
Repair XLSX with Excel and save to new file
Open both files with ZIP editor (e.g. 7Zip)
Find xl/tables/table1.xml
Export both XML files (POI and Excel-repaired)
Diff the files

You have not created your table correctly.
Check:
Did you create header columns in cttable?
Did you create the same header columns through cell.setCellValue?
Remove empty first header column(POI BUG) at the end
CTTable().getTableColumns().removeTableColumn(0);
Put debug into XSSFTable.class, method updateHeaders().
If your table is not created properly, then
XSSFRow row = sheet.getRow(headerRow);
will be NULL in
/**
* Synchronize table headers with cell values in the parent sheet.
* Headers <em>must</em> be in sync, otherwise Excel will display a
* "Found unreadable content" message on startup.
*/
#SuppressWarnings("deprecation")
public void updateHeaders(){
XSSFSheet sheet = (XSSFSheet)getParent();
CellReference ref = getStartCellReference();
if(ref == null) return;
int headerRow = ref.getRow();
int firstHeaderColumn = ref.getCol();
XSSFRow row = sheet.getRow(headerRow);
if (row != null && row.getCTRow().validate()) {
int cellnum = firstHeaderColumn;
for (CTTableColumn col : getCTTable().getTableColumns().getTableColumnArray()) {
XSSFCell cell = row.getCell(cellnum);
if (cell != null) {
col.setName(cell.getStringCellValue());
}
cellnum++;
}
}
}

Related

Issue while writing cells in excel file using apache POI

I am facing issue while writing the data to excel file.
I am using apache POI 4.1.2 version library.
Below is the sample code.
try {
outputStream = new FileOutputStream(EXCEL_FILE_PATH);
} catch (Exception e) {
System.out.println("Exception While writing excel file " + e.getMessage());
}
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("FileCompare");
Row row = sheet.createRow(0);
Cell cellfilename = row.createCell(0);
cellfilename.setCellValue("File Name");
Cell cellfilename1 = row.createCell(1);
cellfilename1.setCellValue("Difference in File 1");
Cell cellfilenam2 = row.createCell(2);
cellfilenam2.setCellValue("Difference in File 2");
for (int diffcol = 1; diffcol < 3; diffcol++) {
for (int i = 1; i < 57; i++) {
Row rows = sheet.createRow(i);
// System.out.println("Difference Coln number " + diffcol);
Cell diffcell = rows.createCell(diffcol);
diffcell.setCellValue("abacds");
/*
* Cell diffcell2 = row.createCell(2); diffcell2.setCellValue("abacds");
*/
}
}
try {
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStream.flush();
outputStream.close();
workbook.close();
}
In this only last column cells is getting saved in excel file , previous cells are kept as blank.
Kindly help and let me know if I am doing something wrong?
Not sure about the actual api but I think you inner loop should create columns and your outer one should create rows like this
for (int row=1:row<57;row++)
{
Row rows = sheet.createRow(row);
for (int diffCol = 1; diffCol < 3; difCol++)
{
Cell diffcell = rows.createCell(diffcol);
diffcell.setCellValue("abacds");
}
}
The problem is that inside your loop you're always using sheet.createRow(i) to retrieve the row you need, but as the docs says (docs that are written not so clear, actually) this method is always recreating a brand new & empty row, deleting the existing one (if a row at that i-position was already present).
It means that each iteration of yuor loop is actually deleting previous rows creating brand new rows: at the end only rows created by the last iteration are surviving!
To solve you're problem, use sheet.createRow(i) only one time in order to create the row at i-position and then only use sheet.getRow(i) to retreive it.
So replace (in your code) the following wrong line
Row rows = sheet.createRow(i);
with the following code
Row row = sheet.getRow(i);
if (row == null) row = sheet.createRow(i);
where new row is created only if it does not already exist!
And you're done, it works like a charm!

Apache POI createTable generates corrupted file when a header's cell contains a line break

I am using Apache POI 4.1.2 to create Excel files in Java. I have a piece of code that creates a table from existing cells and everything used to work fine, untill I had a linebreak inside a header's cell.
I tried to change the table's column name afterward but it didn't fix anything.
Below is a minimal piece of code to reproduce the problem:
public void test() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
// headers
XSSFRow headersRow = sheet.createRow(0);
headersRow.createCell(0).setCellValue("Column1");
headersRow.createCell(1).setCellValue("Column2");
// a second row
XSSFRow row = sheet.createRow(1);
row.createCell(0).setCellValue(1);
row.createCell(1).setCellValue(2);
// create a table
AreaReference area = wb.getCreationHelper().createAreaReference(
new CellReference(sheet.getRow(0).getCell(0)),
new CellReference(sheet.getRow(1).getCell(1))
);
XSSFTable table = sheet.createTable(area);
// styling (no problem here)
sheet.setColumnWidth(0, 5000);
sheet.setColumnWidth(1, 5000);
CTTable cttable = table.getCTTable();
cttable.addNewTableStyleInfo();
XSSFTableStyleInfo style = (XSSFTableStyleInfo) table.getStyle();
style.setName("TableStyleMedium6");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
cttable.addNewAutoFilter().setRef(area.formatAsString());
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setWrapText(true);
headersRow.getCell(0).setCellStyle(cellStyle);
// this file is OK
try (FileOutputStream outputStream = new FileOutputStream("C:\\tmp\\test.xlsx")) {
wb.write(outputStream);
}
// add a line break in a header's cell
headersRow.getCell(0).setCellValue("Column1\nwith a line break");
// this file has a problem
try (FileOutputStream outputStream = new FileOutputStream("C:\\tmp\\test2.xlsx")) {
wb.write(outputStream);
}
// this doesn't fix anything
table.getColumns().get(0).setName("Column1");
try (FileOutputStream outputStream = new FileOutputStream("C:\\tmp\\test3.xlsx")) {
wb.write(outputStream);
}
// neither does this
cttable.getTableColumns().getTableColumnList().get(0).setName("Column1");
try (FileOutputStream outputStream = new FileOutputStream("C:\\tmp\\test4.xlsx")) {
wb.write(outputStream);
}
}
Excel loads text.xlsx properly, but complains about all other files:
We found a problem with some content...
After Excel fixes the files, everything is OK but I would like to get rid of the warning message.
Any help will be appreciated.
Thanks
This is an inaccuracy with XSSFTable.updateHeaders. This method gets called while the table's XML gets written. This is because the table column names always must be synchronized with the cell contents. For example if the cell content is "Column1" and this cell is a column header of a table, then this tables column name also must be "Column1" (XML: <tableColumn id="1" name="Column1"/>).
But for line feeds in column headers, there is a specialty. If the cell content is "Column1\nwith a line break" and this cell is a column header of a table, then this tables column name must be XML as <tableColumn id="1" name="Column1_x000a_with a line break"/>. So "\n" is replaced by "x000a". Also "\r" would must be replaced by "x000d". This is because "\r\n" line breaks will not have the meaning of line break in XML.
So XSSFTable.java - updateHeaders would must be patched that way that "\n" gets replaced by "x000a" and "\r" gets replaced by "x000d".
...
public void updateHeaders() {
XSSFSheet sheet = (XSSFSheet)getParent();
CellReference ref = getStartCellReference();
if (ref == null) return;
int headerRow = ref.getRow();
int firstHeaderColumn = ref.getCol();
XSSFRow row = sheet.getRow(headerRow);
DataFormatter formatter = new DataFormatter();
if (row != null && row.getCTRow().validate()) {
int cellnum = firstHeaderColumn;
CTTableColumns ctTableColumns = getCTTable().getTableColumns();
if(ctTableColumns != null) {
for (CTTableColumn col : ctTableColumns.getTableColumnList()) {
XSSFCell cell = row.getCell(cellnum);
if (cell != null) {
String colName = formatter.formatCellValue(cell);
colName = colName.replace("\n", "_x000a_");
colName = colName.replace("\r", "_x000d_");
col.setName(colName);
}
cellnum++;
}
}
}
tableColumns = null;
columnMap = null;
xmlColumnPrs = null;
commonXPath = null;
}
...
Since XSSFTable.updateHeaders gets called while the table's XML gets written while XSSFWorkbook.write, there is no other way than patching this method. One does not have any chance to change table's XML while XSSFWorkbook.write.

Apache POI Pivot table error when same index is used for both column and row label

I am trying to create a pivot table to do cohort analysis
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
pivotTable.addRowLabel(1);
this is giving me an error while opening the file that the file is corrupt do you want to still open the file, when I say yes and open it, the result looks fine, the only issue is the error.
I did a workaround to have a duplicate column data with different name
for ex:
say column 1 is email added a duplicate column 36 with name dup email and did as shown below, it works fine
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
pivotTable.addRowLabel(35);
why in the first place it failed when I give both column and row label as 1.
Any help is greatly appreciated
If you set pivotTable.addRowLabel(1) using apache poi, then apache poi sets pivot field 1 only to be axisRow but it needs to be dataField too if you also want to pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1). So we neeed to correct this.
Example:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import java.io.*;
class PivotTableTest5 {
private static void setCellData(Sheet sheet) {
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Name");
cell = row.createCell(1);
cell.setCellValue("City");
for (int r = 1; r < 15; r++) {
row = sheet.createRow(r);
cell = row.createCell(0);
cell.setCellValue("Name " + ((r-1) % 4 + 1));
cell = row.createCell(1);
cell.setCellValue("City " + (int)((new java.util.Random().nextDouble() * 3)+1) );
}
}
public static void main(String[] args) {
try {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
//Create some data to build the pivot table on
setCellData(sheet);
XSSFPivotTable pivotTable = sheet.createPivotTable(
new AreaReference(new CellReference("A1"), new CellReference("B15")), new CellReference("H5"));
//Count the second column. This needs to be second column a data field.
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
//Use second column as row label
pivotTable.addRowLabel(1);
//Apache poi sets pivot field 1 (second column) only to be axisRow but it needs to be dataField too.
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(1).setDataField(true);
FileOutputStream fileOut = new FileOutputStream("PivotTableTest5.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

poi cannot write data into .xlsx

the problem is when I tried to write data into cells, the cell either hasn't been created or it just doesn't show the data in it.
For instance,
Row[] rownames = new Row[names.size()];
for(int i = 0; i < names.size(); i++){
rownames[i] = sheet.createRow(i+3);
Cell machine = rownames[i].createCell(0);
machine.setCellType(Cell.CELL_TYPE_STRING);
machine.setCellValue(names.get(i).toString());
}
names[] is an array that contains a list of names.
Cell machine = rownames[i].createCell(0); creates a cell at (i+3,0), in which i means row.
machine.setCellValue(names.get(i).toString()); sets cell value to the corresponding name[i].
I tried print names[] and machine.getStringCellValue(), and both of them can return the exact correct data (like output to console). but there's nothing in xlsx file. many thanks in advance.
EDIT:
Let me explain more clearly, so if everything goes well, the very part of this xlsx file should be like this:
harry | (row 3, col 0)
kate | (row 4, col 0)
jim | (row 5, col 0)
aaron | (row 6, col 0)
...
...
But now the situation is:
| (row 3, col 0)
| (row 4, col 0)
| (row 5, col 0)
| (row 6, col 0)
...
...
Right now the xlsx is 4KB. it contains some other information, which have been put there via this very program. Those parts don't have this problem.
Looks like you create row by same index multiple times in further (non posted) code.
How poi creates XSSFRow:
public XSSFRow createRow(int rownum) {
CTRow ctRow;
XSSFRow prev = _rows.get(rownum);
if(prev != null){
// the Cells in an existing row are invalidated on-purpose, in order to clean up correctly, we
// need to call the remove, so things like ArrayFormulas and CalculationChain updates are done
// correctly.
// We remove the cell this way as the internal cell-list is changed by the remove call and
// thus would cause ConcurrentModificationException otherwise
while(prev.getFirstCellNum() != -1) {
prev.removeCell(prev.getCell(prev.getFirstCellNum()));
}
ctRow = prev.getCTRow();
ctRow.set(CTRow.Factory.newInstance());
}
...
}
So, if row exists and contains cell, all cells with data will be removed.
To avoid this, use CellUtil class:
Get a row from the spreadsheet, and create it if it doesn't exist.
CellUtil.getRow(rowIndex, sheet);
Get a specific cell from a row. If the cell doesn't exist, then create it.
CellUtil.getCell(row, columnIndex);
You have not posted file opening and closing code. Based on description, it seems that you are not writing data back to Excel file. Do something like this:
FileOutputStream out = new FileOutputStream(new File("path of excel file"));
wb.write(out);
wb.close();
out.close();
After executing entire code, then check excel file for the output generated.
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
This is my code...
HSSFFont boldFont;
HSSFFont bodyFont;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("namefile");
HSSFRow row = sheet.createRow((short)0);
//HSSFCellStyle cellStyle = workbook.createCellStyle();
//cellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
//cellStyle.setFillForegroundColor(HSSFColor.LAVENDER.index);
//cellStyle.setFillPattern(HSSFCellStyle.ALIGN_CENTER);
row.setHeightInPoints(23);
sheet.setColumnWidth((short)0, (short)2000);
sheet.setColumnWidth((short)1, (short)3000);
sheet.setColumnWidth((short)2, (short)3000);
sheet.setColumnWidth((short)3, (short)3000);
sheet.setColumnWidth((short)4, (short)3000);
sheet.setColumnWidth((short)5, (short)3000);
sheet.setColumnWidth((short)6, (short)3000);
sheet.setColumnWidth((short)7, (short)3000);
sheet.setColumnWidth((short)8, (short)3000);
sheet.setColumnWidth((short)9, (short)3000);
sheet.setColumnWidth((short)10, (short)3000);
sheet.setColumnWidth((short)11, (short)3000);
row.createCell((short)0).setCellValue("FLT NO");
row.createCell((short)1).setCellValue("LEG");
row.createCell((short)2).setCellValue("DATE");
row.createCell((short)3).setCellValue("AC-REG");
row.createCell((short)4).setCellValue("SCHED DEP");
row.createCell((short)5).setCellValue("OFFBLK");
row.createCell((short)6).setCellValue("AIRBORNE");
row.createCell((short)7).setCellValue("LANDING");
row.createCell((short)8).setCellValue("ONBLK");
row.createCell((short)9).setCellValue("SCHED ARR");
row.createCell((short)10).setCellValue("FUEL_USED_PILOT");
row.createCell((short)11).setCellValue("ACTUAL FUEL");
ProofSheetFPRModel model = new ProofSheetFPRModel();
int rownum = 1;
for (int i=0; i<DataList.size(); i++)
{
model = DataList.get(i);
row = sheet.createRow((short)rownum);
row.createCell((short)0).setCellValue(model.getFlightNo());
row.createCell((short)1).setCellValue(model.getLEG());
row.createCell((short)2).setCellValue(model.getDate());
row.createCell((short)3).setCellValue(model.getAC_REG());
row.createCell((short)4).setCellValue(model.getSCHED_DEP());
row.createCell((short)5).setCellValue(model.getOFF_BLK());
row.createCell((short)6).setCellValue(model.getAIRBORNE());
row.createCell((short)7).setCellValue(model.getLANDG());
row.createCell((short)8).setCellValue(model.getON_BLK());
row.createCell((short)9).setCellValue(model.getSCHED_ARR());
row.createCell((short)10).setCellValue(model.getFUEL_USED_PILOT());
row.createCell((short)11).setCellValue(model.getACTUAL_FUEL());
rownum++;
}
try
{
FileOutputStream out = new FileOutputStream(new File(filePath));
workbook.write(out);
out.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

java program to read specific data

I need java code to read data for specific column from excel sheet. – (lo number, line, voucher no, stloc , quantity ,activity.)
These set of values for a particular column will be used for sql query (jdbc-odbc connection done).
The output for the query will be matched with a column in this sheet (this part ll be done later)
Kindly help.
sample excel sheet
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package excelfilereading;
/**
*
* #author vkantiya
*/
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class Main {
#SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
//
// An excel file name. You can create a file name with a full
// path information.
//
String filename = "FirstExcel.xls";
// Create an ArrayList to store the data read from excel sheet.
//
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
//
// Create a FileInputStream that will be use to read the
// excel file.
//
fis = new FileInputStream(filename);
//
// Create an excel workbook from the file system.
//
HSSFWorkbook workbook = new HSSFWorkbook(fis);
//
// Get the first sheet on the workbook.
//
HSSFSheet sheet = workbook.getSheetAt(0);
//
// When we have a sheet object in hand we can iterator on
// each sheet's rows and on each row's cells. We store the
// data read on an ArrayList so that we can printed the
// content of the excel to the console.
//
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
showExelData(sheetData);
}
private static void showExelData(List sheetData) {
//
// Iterates the data and print it out to the console.
//
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
for (int j = 0; j < list.size(); j++) {
HSSFCell cell = (HSSFCell) list.get(j);
System.out.print(
cell.getRichStringCellValue().getString());
if (j < list.size() - 1) {
System.out.print(", ");
}
}
System.out.println("");
}
}
}
Have a look at Apache POI - the Java API for Microsoft Documents.
It covers
Excel (SS=HSSF+XSSF)
Word (HWPF+XWPF)
PowerPoint (HSLF+XSLF)
OpenXML4J (OOXML)
OLE2 Filesystem (POIFS)
OLE2 Document Props (HPSF)
Outlook (HSMF)
Visio (HDGF) TNEF (HMEF)
Publisher (HPBF)

Categories

Resources