In my application, I have exported the table content to Excel already, but the result excludes the table header. Wondering how to export JTable to Excel include the table header? I tried couple ways, but still can not see the table header in excel, the following is my code:
defautTableModel = new DefaultTableModel(null,columnNames){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
// the jTable row are generated dynamically.
final JTable jTable = new JTable(defautTableModel);
jTable.setLocation(20,60);
jTable.setSize(950,450);
jTable.setRowHeight(25);
JTableHeader jTableHeader = jTable.getTableHeader();
jTableHeader.setLocation(20,30);
jTableHeader.setSize(950,30);
jTableHeader.setFont(new Font(null, Font.BOLD, 16));
jTableHeader.setResizingAllowed(true);
jTableHeader.setReorderingAllowed(true);
jTable.add(jTableHeader);
JScrollPane tablePanel = new JScrollPane(jTable);
tablePanel.setLocation(10,10);
tablePanel.setSize(960,400);
// export data to excel method
public void exportToExcel(){
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
for (int i = 0; i < defautTableModel.getRowCount(); i++) {
Row = sheet.createRow(i);
for (int j = 0; j < defautTableModel.getColumnCount(); j++) {
Cell = Row.createCell(j);
try {
if (defautTableModel.getValueAt(i,j) != null){
Cell.setCellValue(defautTableModel.getValueAt(i,j).toString());
FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData_Output);
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You are only accessing the data columns and you need to get the header ones first.
You can acheive it by different means, either you use the method getColumnName
as ThomasEdwin mentioned in his comment or use columnNames variable that you have provided to your model constructor: new DefaultTableModel(null,columnNames)
Hope it helps
Export Java Swing JTable header with JTable index to Excel
private static void writeToExcell(DefaultTableModel TabR ,TableColumnModel tableM) throws IOException {
try
{
JFileChooser fileChooser = new JFileChooser();
int retval = fileChooser.showSaveDialog(fileChooser);
if (retval == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file != null) {
if (!file.getName().toLowerCase().endsWith(".xls")) {
file = new File(file.getParentFile(), file.getName() + ".xls");
#SuppressWarnings("resource")
Workbook wb = new HSSFWorkbook();
#SuppressWarnings("unused")
CreationHelper createhelper = wb.getCreationHelper();
org.apache.poi.ss.usermodel.Sheet sheet = wb.createSheet();
org.apache.poi.ss.usermodel.Row row = null;
org.apache.poi.ss.usermodel.Cell cell = null;
for (int a=0;a<TabR.getRowCount();a++)
{
row = sheet.createRow(a+1); /* We create an Excel layer Row.
We understand how many rows are in
TabR with GetRowCount from TabR, the
DefaultTableModel of the current JTable,
and add one to it.*/
for (int b=0;b<tableM.getColumnCount();b++)
{
cell = row.createCell(b);/* With the GetColumnCount
function of the existing JTable's
TableColumnModel, we create more
Column in the JTable.*/
cell.setCellValue(TabR.getValueAt(a, b).toString()); /*we give the value of the cell. */
}
}
for (int c=0;c<cell.getRowIndex();c++)
{
row = sheet.createRow(c);
for (int d=0;d<tableM.getColumnCount();d++)
{
cell = row.createCell(d);
cell.setCellValue(tableM.getColumn(d).getHeaderValue().toString());
}
}
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
}
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(B_anaEk.class.getName()).log(Level.ALL, null, ex);
} catch (IOException ex) {
Logger.getLogger(B_anaEk.class.getName()).log(Level.ALL, null, ex);
}
Related
I want to run selenium-webdriver-java-eclipse, using excel file contains multiple excel sheets with different name(sheet1,sheet2,sheet3,...), i need a for loop help me to do that and read from this sheets.
public class ExcelDataConfig {
XSSFWorkbook wb;
XSSFSheet sheet = null;
public ExcelDataConfig(String Excelpath) throws IOException {
// TODO Auto-generated method stub
try {
File file = new File(Excelpath);
// Create an object of FileInputStream class to read excel file
FileInputStream fis = new FileInputStream(file);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
}
}
public String GetData(int sheetNumber, int Row, int Column) {
Iterator<Row> rowIt=sheet.rowIterator();
DataFormatter formatter = new DataFormatter();
XSSFCell cell = sheet.getRow(Row).getCell(Column);
String data = formatter.formatCellValue(cell);
return data;
}
public int GetRowCount(String sheetNumber) {
int row = wb.getSheet(sheetNumber).getLastRowNum();
row = row + 1;
return row;
}
}
try something like this, it is working for me you need to add the sheet numbers and cell numbers at the places of k and j
enter code here
String filePath="C:\\Users\\USER\\Desktop\\Book1.xlsx";// file path
FileInputStream fis=new FileInputStream(filePath);
Workbook wb=WorkbookFactory.create(fis);
ArrayList<String> ls=new ArrayList<String>();
for(int k=0; k<=3;k++)//k =sheet no
{
Sheet sh=wb.getSheetAt(k);
System.out.println(sh);
// int count=0;
for(int i=0;i<=sh.getLastRowNum();i++)
{
System.out.println("row no:"+i);
for(int j=0; j<=4;j++)//j=column no
{
try {
String values=sh.getRow(i).getCell(j).getStringCellValue().trim();
System.out.println(values);
//condetions
/* if(values.contains("condtn1"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}
if(values.contains("condn2"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}*/
}catch(Exception e){
}
}
}
}
}
}
Please try writing similar to something like this:
for (int i = startRow; i < endRow + 1; i++) {
for (int j = startCol; j < endCol + 1; j++) {
testData[i - startRow][j - startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
Cell cell = ExcelWSheet.getRow(i).getCell(j);
testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
}
}
Terms used in method are pretty self explanatory. Let us know if you get stuck or need more info.
I am using APACHE POI 3.0 to add sheets to existing excel sheet. It works fine.
But as APACHE POI has limitations about making charts, I used a template excel file to create charts, which also worked fine, but this always result in new excel file.
If I have an existing excel sheet and I want to add a sheet, having charts, I am not able to do it. As, when I create charts, I use template file and it always makes a new excel file.
so I was wondering if there is any solution of it of adding sheets to excel, where the sheets have charts
public class TagBrowserSelection
{
private static String[] excelBarPlot_Template = { "","barPlot_1Panel_template.xlsx"};
private static String[] excelPieChart_Template = { "","pieChart_1Panel_template.xlsx"};
private static String[] excelPieAndBarPlot_Template = { "","pieAndBarChart_1Panel_template.xlsx"};
private static String REGEX = "";
static public boolean makeTagBrowserSelection(String strOutputFileName, ArrayList<TagBrowserChildPanel> childList, String sheetName, boolean addSheet, ArrayList<Boolean> chartAttributes)
{
// chart attributes
boolean addBarChart = chartAttributes.get(0);
boolean addPieChart = chartAttributes.get(1);
boolean addNoTag = chartAttributes.get(2);
boolean addZeros = chartAttributes.get(3);
REGEX = "^" + sheetName;
Pattern p = Pattern.compile(REGEX);
String[] templateArray = null;
if (addBarChart && addPieChart)
templateArray = excelPieAndBarPlot_Template;
else if (addBarChart)
templateArray = excelBarPlot_Template;
else if (addPieChart)
templateArray = excelPieChart_Template;
try
{
int number = childList.size();
XSSFWorkbook workbook = null;
XSSFWorkbook wb = null;
XSSFSheet sheet = null;
int col_num = 0;
int row_num = 0;
XSSFRow row = null;
XSSFCell cell = null;
// if adding sheet to existing excel file
if (addSheet)
{
FileInputStream fis = new FileInputStream(new File(strOutputFileName));
workbook = new XSSFWorkbook(fis);
fis.close();
// number of existing sheets in excel file
int numberOfSheets = workbook.getNumberOfSheets();
// check is sheetName exists already
if (isSheetExist(sheetName, workbook))
{
int counter = 1;
for (int ii = 0; ii < numberOfSheets; ii++)
{
Matcher m = p.matcher(workbook.getSheetName(ii));
if (m.find())
counter++;
}
sheetName = sheetName + " (" + counter + ")";
}
}
else
{
workbook = new XSSFWorkbook();
}
======================================================================
// if template file needs to be used(if bar chart/pie chart option is selected)
if (templateArray != null)
{
InputStream is = TagBrowserSelection.class.getClassLoader().getResourceAsStream(templateArray[number]);
wb = new XSSFWorkbook(OPCPackage.open(is));
sheet = wb.getSheetAt(0);
// wb.close();
}
else
{
sheet = workbook.createSheet(sheetName);
}
// Freeze top two row
// sheet.createFreezePane(0, 1, 0, 1);
// Filling up the workbook and performing the row/column formatting
for (TagBrowserChildPanel child : childList)
{
// Check if row is already created before(previous tag category)
row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);
// Adding tag category name as header
String tagCategory = child.getSelectedCategory().getName();
cell = row.createCell(col_num);
cell.setCellValue(tagCategory);
row = sheet.getRow(1);
if (row == null)
row = sheet.createRow(1);
// Adding column headers
cell = row.createCell(col_num);
cell.setCellValue("tag");
cell = row.createCell(col_num + 1);
cell.setCellValue("counts");
row_num = 2;
// Adding tag category document summary(name and counts)
ArrayList<TagSummaryItem> tagSummary = child.getTagChartCounts();
for (int i = 0; i < tagSummary.size(); i++)
{
// Check if row is already created before(previous tag category)
row = sheet.getRow(row_num);
if (row == null)
row = sheet.createRow(row_num);
cell = row.createCell(col_num);
if (!addNoTag)
{
if (tagSummary.get(i).m_strTag == "[No Tag]")
continue;
}
if (!addZeros)
{
if (tagSummary.get(i).m_nCount == 0)
continue;
}
cell.setCellValue(tagSummary.get(i).m_strTag);
cell = row.createCell(col_num + 1);
cell.setCellValue(tagSummary.get(i).m_nCount);
row_num++;
}
// auto-size of tag column
sheet.autoSizeColumn(col_num);
col_num = col_num + 3;
}
FileOutputStream out = new FileOutputStream(strOutputFileName);
if (templateArray != null)
{
wb.setSheetName(0, sheetName);
wb.write(out);
wb.close();
}
else
{
workbook.write(out);
workbook.close();
}
out.close();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
Above is my code, its one code. I split into two sections. Section is the one which uses template to make chart excel sheet.
there's the method cloneSheet() in the HSSFWorkbook class. Try it.
I have the code below, and what this does is basically get my data from my table model and put this into a spreadsheet. However upon exporting the data the data is not being kept in the order i specified when sorting my table:
This is defined as below from another method that sorts the table rows and the executes the method saveSingleTableAsExcel(); which exports the data:
.......
sorter = new TableRowSorter<>(tableR.getModel());
tableR.setRowSorter(sorter);
sortKeys = new ArrayList<>();
int columnIndexToSort = 0;
sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
sorter.sort();
saveSingleTableAsExcel();
.......
public void saveSingleTableAsExcel() throws FileNotFoundException{
Map<String,TableModel> models = new HashMap<String,TableModel>();
models.put("Sheet1", modelR);
saveTablesAsExcel(models);
}
public static void saveTablesAsExcel(Map<String,TableModel> models) throws FileNotFoundException{
HSSFWorkbook wb = new HSSFWorkbook();
for (String sheetName : models.keySet()){
createSheet(wb, models.get(sheetName), sheetName);
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HHmmss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); //2014/08/06 16:00:22
//FileOutputStream out = null;
FileOutputStream out = new FileOutputStream("C:\\Users\\tester.xls");
try {
wb.write(out);
out.close();
} catch (IOException e) {
}
}
/**
* Create a Sheet in the workbook using data from the TableModel
*
* #param wb
* #param model
* #param sheetName
*/
private static void createSheet(HSSFWorkbook wb, TableModel model, String sheetName){
Sheet sheet = wb.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
headerRow.setHeightInPoints(12.75f);
HSSFFont boldFont = wb.createFont();
boldFont.setFontHeightInPoints((short)22);
boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle headerStyle = wb.createCellStyle();
// Create the header cells
int numColumns = model.getColumnCount();
for (int col=0; col<numColumns; col++) {
Cell cell = headerRow.createCell(col);
cell.setCellValue(model.getColumnName(col));
cell.setCellStyle(headerStyle);
}
// Set the cell values
int numRows = model.getRowCount();
for (int row=0; row<numRows; row++){
Row sheetRow = sheet.createRow(row+1); // account for header row (0)
for (int col=0; col<numColumns; col++) {
Cell cell = sheetRow.createCell(col);
Object val = model.getValueAt(row, col);
if (val instanceof Number){
cell.setCellValue((double)val);
}
else if (val instanceof Boolean){
cell.setCellValue((Boolean)val);
}
else if (val instanceof String){
cell.setCellValue(((String)val));
}
else if (val instanceof Date){
cell.setCellValue((Date)val);
}
// else {
// cell.setCellValue(val.toString());
// }
}
}
}
How can i retain the same order as the model, which is being sorted by the first column (column 0)?
Is your sort method using a comparator or equals method that haven't been overwritten? That's my best guess without seeing the sort method.
I've a web project, where grid view is displayed from database. Arraylist name is leadSchoolList. So, I kept a button, when clicked it runs a method(named:-actionExportToExcel) in Struts action class. Right now I am able to export list elements to excel.
But the problem I'm facing is opening up that exported excel Sheet on window. So another method(named:-open) is called inside actionExportToExcel. But I don't know where I'm wrong, so can anyone help me?
public String actionExportToExcel(){
try {
FileOutputStream fileOut = new FileOutputStream("D:/poi-test.xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
leadSchoolList = leadSchoolService.getAllLeadSchool();
for(int rowNum = 0; rowNum < leadSchoolList.size(); rowNum++){
HSSFRow row = sheet.createRow(rowNum);
//for(int colNum = 0; colNum < 5; colNum++ ){
HSSFCell cell1 = row.createCell(0);
LeadSchool leadSchool = leadSchoolList.get(rowNum);
cell1.setCellValue(leadSchool.getLeadSchool_String_LSchool_ID());
HSSFCell cell2 = row.createCell(1);
cell2.setCellValue(leadSchool.getLeadSchool_String_Name());
HSSFCell cell3 = row.createCell(2);
cell3.setCellValue(leadSchool.getLeadSchool_String_Address());
HSSFCell cell4 = row.createCell(3);
cell4.setCellValue(leadSchool.getLeadSchool_String_Phone_No());
HSSFCell cell5 = row.createCell(4);
cell5.setCellValue(leadSchool.getLeadSchool_String_Remarks());
System.out.println("Successfully exported to Excel");
}
try {
wb.write(fileOut);
// fileOut.flush();
open(fileOut);
//fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
addActionError("The process cannot access the file because it is being used by another process");
e.printStackTrace();
}
return SUCCESS;
}
private void open(FileOutputStream f) {
String[] cmd = new String[4];
try{
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = "start";
cmd[3] = "D:/poi-test.xls";
Runtime.getRuntime().exec(cmd);
//Runtime.getRuntime().exec("cmd.exe /c start D:/poi-test.xls");
System.out.print("file opened");
}
catch(Exception e){
e.printStackTrace();
}
}
Fortunately found the solution myself. .First need to run flush() and close() method and then the second(named:-open) method. Inside open method, instead of R
Runtime.getRuntime().exec(cmd);
i expanded it into two lines:-
Runtime run = Runtime.getRuntime();
Run.exec(cmd);
Thats it..:D
I am trying to export data from a database to Excel. I have the data exported and currently being stored in an ArrayList (this can be changed). I have been able to export the data to excel but all of the values are being exported as Strings, I need them to keep their data type i.e currency/numeric.
I am using Apache POI and am having difficult with setting the data type of the fields to anything other than String. Am I missing something? Can someone please advise me on a better way of doing this? Any assistance on this would be greatly appreciated.
public static void importDataToExcel(String sheetName, ArrayList header, ArrayList data, File xlsFilename, int sheetNumber)
throws HPSFException, FileNotFoundException, IOException {
POIFSFileSystem fs = new POIFSFileSystem();
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(xlsFilename));
HSSFSheet sheet = wb.createSheet(sheetName);
int rowIdx = 0;
short cellIdx = 0;
// Header
HSSFRow hssfHeader = sheet.createRow(rowIdx);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
for (Iterator cells = header.iterator(); cells.hasNext();) {
HSSFCell hssfCell = hssfHeader.createCell(cellIdx++);
hssfCell.setCellStyle(cellStyle);
hssfCell.setCellValue((String) cells.next());
}
// Data
rowIdx = 1;
for (Iterator rows = data.iterator(); rows.hasNext();) {
ArrayList row = (ArrayList) rows.next();
HSSFRow hssfRow = (HSSFRow) sheet.createRow(rowIdx++);
cellIdx = 0;
for (Iterator cells = row.iterator(); cells.hasNext();) {
HSSFCell hssfCell = hssfRow.createCell(cellIdx++);
hssfCell.setCellValue((String) cells.next());
}
}
Logfile.log("sheetNumber = " + sheetNumber);
wb.setSheetName(sheetNumber, sheetName);
try {
FileOutputStream out = new FileOutputStream(xlsFilename);
wb.write(out);
out.close();
} catch (IOException e) {
throw new HPSFException(e.getMessage());
}
}
You need to check for the class of your cell value before you cast:
public static void importDataToExcel(String sheetName, List<String> headers, List<List<Object>> data, File xlsFilename, int sheetNumber)
throws HPSFException, FileNotFoundException, IOException {
POIFSFileSystem fs = new POIFSFileSystem();
Workbook wb;
try {
wb = WorkbookFactory.create(new FileInputStream(xlsFilename));
} catch (InvalidFormatException ex) {
throw new IOException("Invalid workbook format");
}
Sheet sheet = wb.createSheet(sheetName);
int rowIdx = 0;
int cellIdx = 0;
// Header
Row hssfHeader = sheet.createRow(rowIdx);
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
for (final String header : headers) {
Cell hssfCell = hssfHeader.createCell(cellIdx++);
hssfCell.setCellStyle(cellStyle);
hssfCell.setCellValue(header);
}
// Data
rowIdx = 1;
for (final List<Object> row : data) {
Row hssfRow = sheet.createRow(rowIdx++);
cellIdx = 0;
for (Object value : row) {
Cell hssfCell = hssfRow.createCell(cellIdx++);
if (value instanceof String) {
hssfCell.setCellValue((String) value);
} else if (value instanceof Number) {
hssfCell.setCellValue(((Number) value).doubleValue());
} else {
throw new RuntimeException("Cell value of invalid type " + value);
}
}
}
wb.setSheetName(sheetNumber, sheetName);
try {
FileOutputStream out = new FileOutputStream(xlsFilename);
wb.write(out);
out.close();
} catch (IOException e) {
throw new HPSFException(e.getMessage());
}
}
I have also added in generics - this makes the code a lot more readable. Also you need to avoid using the actual class where possible and use the interface, for example List not ArrayList and Row not HSSFRow.