Hi i am new to writing data to excel however after doing much research and reading documentation I have done it.
My Problem:
When string data is stored in my array and written it to excel however it does not put it in one column (which is what I want) it spaces each string out in a column to the right of it in a diagonal descent in my spread sheet. A picture is below.
What I want is for each string/name to be put in one column under each other. Any suggestions would be appreciated.
Code Snippet:
System.out.println("Write data to an Excel Sheet");
FileOutputStream out = new FileOutputStream("C:/Users/hoflerj/Desktop/text2excel/finish.xlsx");
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet spreadSheet = workBook.createSheet("clientid");
XSSFRow row;
XSSFCell cell;
for(int i=0;i<arr.size();i++){
row = spreadSheet.createRow((short) i);
cell = row.createCell(i);
System.out.println(arr.get(i));
cell.setCellValue(arr.get(i).toString());
}
System.out.println("Done");
workBook.write(out);
arr.clear();
out.close();
You are increasing column index as well.
Just change from:
cell = row.createCell(i);
To:
cell = row.createCell(0);
So the For Loop will be like:
for(int i=0;i<arr.size();i++){
row = spreadSheet.createRow((short) i);
cell = row.createCell(0);
System.out.println(arr.get(i));
cell.setCellValue(arr.get(i).toString());
}
Or with fewer lines:
for(int i=0;i<arr.size();i++){
row = spreadSheet.createRow((short) i);
row.createCell(0).setCellValue( arr.get(i).toString() );
System.out.println(arr.get(i));
}
Related
I am writing some data into excel file using Apache POI but for some reason the file shows only the last record (1 record only). I have list of POLJO that I am passing. I am also iterating through the cells but all I get is just one record.
Method to write in excel
public void writeToExcel(List<NYProgramTO> to){
try {
Workbook workBook = new HSSFWorkbook();
CreationHelper helper = workBook.getCreationHelper();
Sheet sheet = workBook.createSheet("NY_PPA_P3_Sheet");
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("First Name");
headerRow.createCell(1).setCellValue("Last Name");
headerRow.createCell(2).setCellValue("Policy Number");
headerRow.createCell(3).setCellValue("Zip Code");
headerRow.createCell(4).setCellValue("Date of Birth");
if(to != null){
int size = to.size();
for(int i = 0; i < size; i++){
NYProgramTO nyP= to.get(i);
Row row = sheet.createRow(1);
row.createCell(0).setCellValue(nyP.getFirstName());
row.createCell(1).setCellValue(nyP.getLastName());
row.createCell(2).setCellValue(nyP.getPolicyNumber());
row.createCell(3).setCellValue(nyP.getZipCode());
row.createCell(4).setCellValue(nyP.getDateOfBirth());
}
}
FileOutputStream stream = new FileOutputStream("NY_PPA_P3.xlsx");
workBook.write(stream);
stream.close();
System.out.println("NY_PPA_P3.xlsx created successfully.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
If by "only one record" you mean that only one row is appearing, this is probably easily fixable by making sure that you increment the Row that is being created before writing the Cells.
Try changing:
Row row = sheet.createRow(1);
to:
Row row = sheet.createRow(i+1);
I am reading the excel sheet using Apache poi in java and I am using CellRangeAddress to get the region.
Case1: If I am giving 2-3 data for merging and going for next cell then it's ok.
I'm getting the next merged region .
Case2: If I am giving more than 6 values and going for next region, then It is showing IndexOutofBoundException for merged region
Here The Code:
List<OrganizationDB> orgList = new ArrayList<OrganizationDB>();
List<EmployeeDB> empList;
XSSFWorkbook workBook;
XSSFSheet excelSheet;
XSSFRow row;
XSSFCell cells;
TreeViewer treeViewer = null;
File excelFile = new File("D:\\ExcelExport\\ExcelSheet2.xls");
FileInputStream fis;
if (excelFile.exists()) {
fis = new FileInputStream(excelFile);
workBook = new XSSFWorkbook(fis);
excelSheet = workBook.getSheetAt(0);
int count = 1;
while (count <= excelSheet.getLastRowNum()) {
CellRangeAddress region = excelSheet.getMergedRegion(count);
row = excelSheet.getRow(count);
//XSSFCell cell = row.getCell(0);
orgDb = new OrganizationDB();
orgDb.setOrganizationName(row.getCell(0).getStringCellValue());
orgDb.setCityName(row.getCell(4).getStringCellValue());
orgDb.setStateName(row.getCell(5).getStringCellValue());
empList = new ArrayList<EmployeeDB>();
while(count<=region.getLastRow()) {
row = excelSheet.getRow(count);
empDb = new EmployeeDB();
empDb.setCompanyName(row.getCell(0).getStringCellValue());
empDb.setEmpID(row.getCell(1).getStringCellValue());
empDb.setEmpName(row.getCell(2).getStringCellValue());
empDb.setPhoneNo((int) row.getCell(3).getNumericCellValue());
empList.add(empDb);
orgDb.setEmpList(empList);
count++;
}
orgList.add(orgDb);
}
I see a logic in your code, which I do not fully understand. Could you check it please?
You have one counter count used by two nested while loops.
while (count <= excelSheet.getLastRowNum()) {
CellRangeAddress region = excelSheet.getMergedRegion(count);
...
while(count<=region.getLastRow()){
...
count++;
perhaps there are two merged regions with rows 1 to 3 and 4 to 6, then after first run of your top while your count = 3, because nested while increased it.
Then code tries to get mergedRegion(3) and
there is no mergedRegion with the index 3.
It must be mergedRegion(2) with next set of rows instead...
I guess you have to use different counters for mergedRegions and rows in them.
I am writing numeric cells to a new excel file 'Test.xlsx' using POI.
I first insert 2 rows with 2 columns each with values:
Row 1 --> 10 (Cell A1), 20
Row 2 --> 15, 20 (Cell B2)
For row 3, column 1, I set the formula SUM(A1:B2).
XSSFWorkbook wb = null;
String absPath = "C:\excel\Test.xlsx";
File f2 = createFileIfDirExist(absPath); //method will return handle if file created successfully
if (f2 != null) {
wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("MySheet");
if (sheet != null) {
XSSFRow row0 = sheet.createRow(0);
XSSFCell cell0 = row0.createCell(0);
cell0.setCellValue(10);
XSSFCell cell1 = row0.createCell(1);
cell1.setCellValue(20);
XSSFRow row1 = sheet.createRow(0);
XSSFCell cell2 = row1.createCell(0);
cell2.setCellValue(15);
XSSFCell cell3 = row1.createCell(1);
cell3.setCellValue(20);
XSSFRow row2 = sheet.createRow(0);
XSSFCell cell4 = row2.createCell(0);
cell4.setCellType(Cell.CELL_TYPE_FORMULA);
cell4.setCellFormula("SUM(A1:B2)");
FileOutputStream outFile = new FileOutputStream(new File(f2));
wb.write(outFile);
outFile.close();
f2.close();
// call method to evaluate formulaEval.evaluateFormulaCell(cell) on every cell in sheet.
}
}
In my actual implementation, i create these sheets, rows and cells dynamically using user input and using loops which I have not used here. It's a basic version of what my code does.
Now, after I run this program, I see that the file is created. I open the file and see that the cell corresponding to cell A3 (formula cell) has the value 65. However, when I close the file, I get the prompt 'want to save your changes to create.xlsx'?
I unzipped create.xlsx before and after clicking on the save for the above prompt and see that the formula cell has the same values for tags F and V in MySheet.xml.
I also noticed that the xml file calcChain.xml is missing before I manually save the excel file and it appears once I save it manually.
Am I missing something to get rid of the prompt when I close the excel? Any pointers will be greatly appreciated.
I need to add a hyperlink in XLS cell which should be linked to the file in my local drive using Java. Here is my code.
I need to link the corresponding file from the local folder to the corresponding cell in the XLs.
I'd tried to add hyperlink, but i can able add only URL in the not the file from the local disk. Please help me
public boolean to_write_xls( int max, List <String> temp_1,List <String> temp_2,List <String> temp_3,List <String> temp_4,List <String> temp_5 ) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Analyzed Result");
HSSFRow rowhead = sheet.createRow((short) 0);
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.ORANGE.index);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_THICK);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
rowhead.createCell((short) 0).setCellValue("Passed TC's ");
rowhead.createCell((short) 1).setCellValue("CRC:Failure ");
rowhead.createCell((short) 2).setCellValue("unexpected RRC PDU");
rowhead.createCell((short) 3).setCellValue("PCallback Error ");
rowhead.createCell((short) 4).setCellValue("Piggybacked NAS PDU");
/* for (int i=0; i<5; i++){
// sheet.setColumnWidth(i,4000);
sheet.autoSizeColumn((short)i);
}*/
Iterator<Cell> ct = rowhead.iterator();
int i=0;
while(ct.hasNext()){
Cell cell = (Cell) ct.next();
cell.setCellStyle(style);
sheet.autoSizeColumn((short)i);
i ++;
}
CellStyle style_r = workbook.createCellStyle();
style_r.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style_r.setBorderTop(HSSFCellStyle.BORDER_THIN);
style_r.setBorderRight(HSSFCellStyle.BORDER_THIN);
style_r.setBorderLeft(HSSFCellStyle.BORDER_THIN);
i=0;
while (i < max ) {
HSSFRow row = sheet.createRow((short) i+2);
row.createCell((short) 0).setCellValue(temp_1.get(i));
row.createCell((short) 1).setCellValue(temp_2.get(i));
row.createCell((short) 2).setCellValue(temp_3.get(i));
row.createCell((short) 3).setCellValue(temp_4.get(i));
row.createCell((short) 4).setCellValue(temp_5.get(i));
Iterator<Cell> rw = row.iterator();
while(rw.hasNext()){
Cell cell = (Cell) rw.next();
cell.setCellStyle(style_r);
}
i++;
}
try {
FileOutputStream Fout =
new FileOutputStream(new File(fin+"\\Result.xls"));
workbook.write(Fout);
Fout.close();
//System.out.println("Excel written successfully..with the file name directory-----> D:\\_Analyzed_Result\\Result.xls");
Runtime.getRuntime().exec("cmd /c start "+fin+"\\Result.xls");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Above code is not working. so I find the some other code which is working fine, which is used to add a hyperlink in the cell.
CellStyle hlink_style = workbook.createCellStyle();
Font hlink_font = workbook.createFont();
hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(Font.COLOR_RED);
hlink_style.setFont(hlink_font);
Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_FILE);
Cell cell = null;
cell=row.createCell((short) 1);
cell.setCellValue("Go to Result");
path_f="D://Result.xls";
link.setAddress(path_f);
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
It works 100% fine!!
Developers can add hyperlinks to external Excel files by calling the Add method of Hyperlinks collection. The Add method takes the following parameters:
Cell Name , represents the cell name where the hyperlink will be added
Number of Rows , represents the number of rows in this hyperlink range
Number of Columns , represents the number of columns of this hyperlink range
URL , represents the address of the external Excel file that will be used as a hyperlink
[Java]
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Obtaining the reference of the first worksheet.
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);
//Setting a value to the "A1" cell
Cells cells = sheet.getCells();
Cell cell = cells.get("A1");
cell.setValue("Visit Aspose");
//Setting the font color of the cell to Blue
Style style = cell.getStyle();
style.getFont().setColor(Color.getBlue());
//Setting the font of the cell to Single Underline
style.getFont().setUnderline(FontUnderlineType.SINGLE);
cell.setStyle(style);
HyperlinkCollection hyperlinks = sheet.getHyperlinks();
//Adding a link to the external file
hyperlinks.add("A5", 1, 1, "C:\\book1.xls");
//Saving the Excel file
workbook.save("c:\\book2.xls");
You can create hyperlink in excel sheet using this java code
File veri1 = new File("your_ file_path");
FileInputStream inputStream_ED1 = new FileInputStream(veri1);
HSSFWorkbook workbook_ED1 = new HSSFWorkbook(inputStream_ED1);
HSSFSheet sheet_ED1 = workbook_ED1.getSheet("Result");
CreationHelper createHelper = workbook_ED1.getCreationHelper();
HSSFCellStyle hlinkstyle = workbook_ED1.createCellStyle();
HSSFFont hlinkfont = workbook_ED1.createFont();
hlinkfont.setUnderline(HSSFFont.U_SINGLE);
hlinkfont.setColor(HSSFColor.BLUE.index);
hlinkstyle.setFont(hlinkfont);
Iterator<Row> riterator_ED1 = sheet_ED1.iterator();
Row row_ED1 = sheet_ED1.createRow(sheet_ED1.getLastRowNum()+1);
if(sheet_ED1.getLastRowNum()==0){
}
Cell DeviceName = row_ED1.createCell(0);
DeviceName.setCellValue(DeviceID.toString());
Cell Module = row_ED1.createCell(1);
Module.setCellValue(module.toString());
Cell SubModule1 = row_ED1.createCell(2);
SubModule1.setCellValue(SubModule.toString());
Cell ScenarioID1 = row_ED1.createCell(3);
ScenarioID1.setCellValue(ScenarioID.toString());
Cell TestcaseID = row_ED1.createCell(4);
TestcaseID.setCellValue(TestCaseID.toString());
Cell TCDescription = row_ED1.createCell(5);
TCDescription.setCellValue(testcasedis.toString());
Cell ExpectedResult1 = row_ED1.createCell(6);
ExpectedResult1.setCellValue(ExpectedResult.toString());
Cell ActualResult1 = row_ED1.createCell(7);
ActualResult1.setCellValue(ActualResult.toString());
Cell Status1 = row_ED1.createCell(8);
Status1.setCellValue(Status.toString());
Cell time = row_ED1.createCell(9);
time.setCellValue(Time.toString());
Cell ExecutionDate1 = row_ED1.createCell(10);
ExecutionDate1.setCellValue(ExecutionDate.toString());
HSSFHyperlink link = (HSSFHyperlink)createHelper.createHyperlink(Hyperlink.LINK_URL);
Cell ss = row_ED1.createCell((short) 11);
ss.setCellValue(sspath.toString());
link = (HSSFHyperlink)createHelper.createHyperlink(Hyperlink.LINK_FILE);
link.setAddress(sspath.toString());
ss.setHyperlink(link);
ss.setCellStyle(hlinkstyle);
FileOutputStream
os_ED1 = new FileOutputStream(veri1);
workbook_ED1.write(os_ED1);
os_ED1.close();
workbook_ED1.close();
inputStream_ED1.close();
I'm using apache poi to create an excel document. To create new sheet in workbook I write next code:
Workbook wb = new HSSFWorkbook();
Sheet sh = wb.createSheet();
this code create and add sheet to workbook. But I want to create sheet formerly and then add it to workbook. Smth like this:
Sheet sh = new HSSFSheet();
wb.addSheet(sh);
I need such thing, because I want to copy data from one sheet of one workbook to another sheet of another workbook(Workbook interface has method Sheet cloneSheet(int)). But Workbook interface doesn't have method like addSheet(Sheet sh).
Also HSSFWorkbook is final class so I can't extend it to implement add method
How can I do this?
You can't just take a Sheet object from one Workbook, and add it to a different Workbook.
What you'll need to do is to open the old workbook and the new workbooks at the same time, and create the sheet in the new workbook. Next, clone all the styles you used in the old sheet onto the new one (HSSFCellStyle has a method for cloning a style from one workbook to another). Finally, iterate over all the cells and copy them over.
You should use RangeCopier.
XSSFWorkbook workbookFrom = new XSSFWorkbook(new File("/path/to/workbookFrom.xlsx"));
XSSFSheet sheetFrom = workbookFrom.getSheetAt(0);
XSSFWorkbook workbookTo = new XSSFWorkbook(new File("/path/to/workbookTo.xlsx"));
XSSFSheet sheetTo = workbookTo.createSheet("sheet1");
workbookTo.setSheetOrder("sheet1", 0);
XSSFRangeCopier xssfRangeCopier = new XSSFRangeCopier(sheetFrom, sheetTo);
int lastRow = sheetFrom.getLastRowNum();
int lastCol = 0;
for (int i = 0; i < lastRow; i++) {
Row row = sheetFrom.getRow(i);
if (row != null) {
if (row.getLastCellNum() > lastCol) {
lastCol = row.getLastCellNum();
}
sheetTo.setDefaultRowHeight(sheetFrom.getDefaultRowHeight());
}
}
for (int j = 0; j < lastCol; j++) {
sheetTo.setColumnWidth(j, sheetFrom.getColumnWidth(j));
}
CellRangeAddress cellAddresses = new CellRangeAddress(0, lastRow, 0, lastCol);
xssfRangeCopier.copyRange(cellAddresses, cellAddresses, true, true);
workbookTo.write(new FileOutputStream(new File("/path/to/worksheetTo.xlsx")));
POI version < v4.0
Okay I tried to do what Gagravarr said above. This solution works for me. This code will work if the sheets don't have tables, etc. If the sheets contain simple text (String, boolean, int etc), formulas, this solution will work.
Workbook oldWB = new XSSFWorkbook(new FileInputStream("C:\\input.xlsx"));
Workbook newWB = new XSSFWorkbook();
CellStyle newStyle = newWB.createCellStyle(); // Need this to copy over styles from old sheet to new sheet. Next step will be processed below
Row row;
Cell cell;
for (int i = 0; i < oldWB.getNumberOfSheets(); i++) {
XSSFSheet sheetFromOldWB = (XSSFSheet) oldWB.getSheetAt(i);
XSSFSheet sheetForNewWB = (XSSFSheet) newWB.createSheet(sheetFromOldWB.getSheetName());
for (int rowIndex = 0; rowIndex < sheetFromOldWB.getPhysicalNumberOfRows(); rowIndex++) {
row = sheetForNewWB.createRow(rowIndex); //create row in this new sheet
for (int colIndex = 0; colIndex < sheetFromOldWB.getRow(rowIndex).getPhysicalNumberOfCells(); colIndex++) {
cell = row.createCell(colIndex); //create cell in this row of this new sheet
Cell c = sheetFromOldWB.getRow(rowIndex).getCell(colIndex, Row.CREATE_NULL_AS_BLANK ); //get cell from old/original WB's sheet and when cell is null, return it as blank cells. And Blank cell will be returned as Blank cells. That will not change.
if (c.getCellType() == Cell.CELL_TYPE_BLANK){
System.out.println("This is BLANK " + ((XSSFCell) c).getReference());
}
else { //Below is where all the copying is happening. First It copies the styles of each cell and then it copies the content.
CellStyle origStyle = c.getCellStyle();
newStyle.cloneStyleFrom(origStyle);
cell.setCellStyle(newStyle);
switch (c.getCellTypeEnum()) {
case STRING:
cell.setCellValue(c.getRichStringCellValue().getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cell.setCellValue(c.getDateCellValue());
} else {
cell.setCellValue(c.getNumericCellValue());
}
break;
case BOOLEAN:
cell.setCellValue(c.getBooleanCellValue());
break;
case FORMULA:
cell.setCellValue(c.getCellFormula());
break;
case BLANK:
cell.setCellValue("who");
break;
default:
System.out.println();
}
}
}
}
}
//Write over to the new file
FileOutputStream fileOut = new FileOutputStream("C:\\output.xlsx");
newWB.write(fileOut);
oldWB.close();
newWB.close();
fileOut.close();
If your requirement is to copy full sheets without leaving or adding anything. I think The process of elimination works better and faster then the above code. And you don't have to worry about losing formulas, drawings, tables, styles, fonts, etc.
XSSFWorkbook wb = new XSSFWorkbook("C:\\abc.xlsx");
for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
if (!wb.getSheetName(i).contentEquals("January")) //This is a place holder. You will insert your logic here to get the sheets that you want.
wb.removeSheetAt(i); //Just remove the sheets that don't match your criteria in the if statement above
}
FileOutputStream out = new FileOutputStream(new File("C:\\xyz.xlsx"));
wb.write(out);
out.close();
POI version >= v4.0
As of version 4.0, Cell.CELL_TYPE_BLANK and Row.CREATE_NULL_AS_BLANK don't exist (they deprecated). Use CellType.* and Row.MissingCellPolicy.* instead.