I wonder how to autoSize the columns in Excel doc.
When I run this code it don't do a jack shit in the document. And I can't really find out what is wrong!
Literally, nothing is autoSized in the document. I don't understand what could be wrong!! Very frustrating problem..
Also, I would be happy to get some feedback on the code, do I practice bad coding habits?
Thanks!
Here is my code:
try
{
FileInputStream myxls = new FileInputStream("/Users/xxxxxx/Desktop/tryIt.xls");
HSSFWorkbook workbook = new HSSFWorkbook(myxls);
HSSFSheet sheet = workbook.getSheetAt(0);
int lastRow=sheet.getLastRowNum();
HSSFCellStyle styleRowHeading = workbook.createCellStyle();
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont fontRowHeading = workbook.createFont();
HSSFFont font = workbook.createFont();
fontRowHeading.setBold(true);
fontRowHeading.setFontName(HSSFFont.FONT_ARIAL);
fontRowHeading.setFontHeightInPoints((short) 14);
styleRowHeading.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
styleRowHeading.setFillPattern(FillPatternType.SOLID_FOREGROUND);
styleRowHeading.setBorderTop(BorderStyle.MEDIUM);
styleRowHeading.setBorderBottom(BorderStyle.MEDIUM);
styleRowHeading.setBorderLeft(BorderStyle.MEDIUM);
styleRowHeading.setBorderRight(BorderStyle.MEDIUM);
styleRowHeading.setFont(fontRowHeading);
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)12);
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderTop(BorderStyle.MEDIUM);
style.setBorderBottom(BorderStyle.MEDIUM);
style.setBorderLeft(BorderStyle.MEDIUM);
style.setBorderRight(BorderStyle.MEDIUM);
style.setFont(font);
// Create heading
if(lastRow <=0){
Row rowHeading = sheet.createRow(lastRow);
rowHeading.createCell(0).setCellValue("TEST1");
rowHeading.createCell(1).setCellValue("TEST2");
rowHeading.createCell(2).setCellValue("TEST3");
rowHeading.createCell(3).setCellValue("TEST4");
for(int i = 0; i < 4; i++){
rowHeading.getCell(i).setCellStyle(styleRowHeading);
}
}
Row row = sheet.createRow(++lastRow);
int i = 0;
org.apache.poi.ss.usermodel.Cell cellId = row.createCell(i);
org.apache.poi.ss.usermodel.Cell cellId1 = row.createCell(i+=1);
org.apache.poi.ss.usermodel.Cell cellId2 = row.createCell(i+=1);
org.apache.poi.ss.usermodel.Cell cellId3 = row.createCell(i+=1);
cellId.setCellValue(todaysDate);
cellId1.setCellValue(txt_year.getText());
cellId2.setCellValue(txt_correct.getText());
cellId3.setCellValue(txt_errors.getText());
cellId.setCellStyle(style);
cellId1.setCellStyle(style);
cellId2.setCellStyle(style);
cellId3.setCellStyle(style);
// Autofit
for(int w = 0; w < 5; w++){
sheet.autoSizeColumn(w);
}
myxls.close();
FileOutputStream output_file =new FileOutputStream(new File("/Users/xxxx/Desktop/tryIt.xls"));
//write changes
workbook.write(output_file);
output_file.close();
System.out.println("SUCCESSSSSSSSS!");
}catch(Exception e){
System.out.println(e.getMessage());
}
I assume HSSFCellStyle might be causing issues here, could you change to CellStyle and check once if you see any formatting changes:
CellStyle style=null;
XSSFFont defaultFont= wb.createFont();
defaultFont.setFontHeightInPoints((short)10);
defaultFont.setFontName("Arial");
defaultFont.setColor(IndexedColors.BLACK.getIndex());
defaultFont.setBold(false);
defaultFont.setItalic(false);
XSSFFont font= wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("Arial");
font.setColor(IndexedColors.WHITE.getIndex());
font.setBold(true);
font.setItalic(false);
style=row.getRowStyle();
style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFont(font);
Key things to keep in mind:
Let's understand the basic difference between HSSFWorkbook and XSSFWorkbook
HSSFWorkbook: This class has methods to read and write Microsoft Excel files in .xls format.
XSSFWorkbook: This class has methods to read and write Microsoft Excel and OpenOffice xml files in .xls or .xlsx format.
SXSSF: it is an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited
Workbook
This is the super-interface of all classes that create or maintain
Excel workbooks. It belongs to the org.apache.poi.ss.usermodel package
and both the above mentioned XSSF, HSSF and SXSSF are implementations of
WORKBOOK
Hence, my suggestion would be to until-unless utmost necessary, i.e, you need a specific feature for xlsx or xls, just go with the workbook implementation
Most of the styling changes are hit and trial. You need to keep
digging iterating with to finally find what you need.
Suggestions:
If you code for just HSSF via HSSFWorkbook, you can only work with .xls files. I'd suggest you go for the common ones wherever possible (workbook)
Your loading code should be something like:
Workbook wb = WorkbookFactory.create(new File("test.xls"));
Sheet s = wb.getSheetAt(0);
....
Now, it will auto-detect the type of the file and give you back a working object for either .xls or .xlsx based on what it finds. Also, wherever possible try to keep the styling and designing parts generic and version independent. That way the same code could be re-used for both formats.
If you need to have any specific feature which require either XSSF
or HSSF and can't use just the Workbook then do a check for the
type first like this:
Workbook wb = WorkbookFactory.create(myExcelFile);
Then you can check the exact type created by the factory:
if (wb instanceof HSSFWorkbook) {
// do whatever
} else if (wb instanceof SXSSFWorkbook) {
// do whatever
} else if (wb instanceof XSSFWorkbook) {
// do whatever
}
Related
I am working to generate excel using java apache poi
i just need to beautify it (with border)
below is the excel that i have successfuly create
and here is the excel that i wanted (see those border and currency and background color)
heres some of my code to generate the excel
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("sheet1");
Row row = sheet.createRow(rowIndex);
row.createCell(0).setCellValue("Product Name");
row.createCell(1).setCellValue("name");
FileOutputStream fileOut = new FileOutputStream("excel.xlsx");
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
I assume you'd need to break down the creation of your cell in this format first before applying any style onto it:
Cell cell1 = row.createCell(0);
cell1.setCellValue("Product Name");
Later,
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderTop((short) 1); // single line border
cellStyle.setBorderBottom((short) 1); // single line border
...//add many others here
cell1.setCellStyle(cellStyle); //apply that style to the cell
Simple way is to create a cellStyle at first and then just go ahead with numerous cell creations as per the application requirement! Next, just loop into each cell to apply the cellStyle if it is a common behavior that you need for all.
Hope that helps!
I have a problem with HSSFWorkbook object. I have a XLS template, where row no 14 is light gray, and next rows are populated with bean values.
During generation of the report, I want to change the date style for which I am writing below code but it's changing the whole tempalate.
workbook = (HSSFWorkbook) WorkbookFactory.create(new FileInputStream(finalFilePath));
sheet = workbook.getSheetAt(0);
workbook.setActiveSheet(0);
CreationHelper creationHelper = workbook.getCreationHelper();
HSSFCellStyle importDataDateStyle = workbook.createCellStyle();
importDataDateStyle.setDataFormat(creationHelper.createDataFormat().getFormat("M/d/yyyy"));
BeanClass bean = new BeanClass();
if (bean.getLastDate() != null) {
migrationBeanRow.createCell(6).setCellValue(lastDate);
} else {
migrationBeanRow.createCell(6).setCellValue(notAvailable);
}
migrationBeanRow.getCell(6).setCellStyle(cellStyleDate);
workbook.write(fileOut);
workbook.close();
This code is working correctly for xlsx(XSSFWorkbook) using XSSFStyle format but changing template for when trying for xls(HSSFWorkbook) file.
Pleas find below template snippet before and after file generation.
pre code template
post code template(Date format is coming as expected but template header color is changing from gray to green)
How can i make all cells in a sheet unlocked by default?
This snippet creates a sheet with all cells locked
SXSSFWorkbook wb = new SXSSFWorkbook();
Sheet sheet = wb.createSheet("Results");
Row row = sheet.createRow(rowCounter);
Cell cell = row.createCell(counter);
cell.setCellValue("test");
This snippet causes some corrupt data when trying to open the excel file
SXSSFWorkbook wb = new SXSSFWorkbook();
Sheet sheet = wb.createSheet("Results");
Row row = sheet.createRow(rowCounter);
Cell cell = row.createCell(counter);
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setLocked(false);
cell.setCellStyle(cellStyle);
cell.setCellValue("test");
This snippet doesn't cause any problems, but it also does unlock the cells. I can modify all the cells, but if i click on "format", the "Lock Cells" link is highlighted.
SXSSFWorkbook wb = new SXSSFWorkbook();
Sheet sheet = wb.createSheet("Results");
Row row = sheet.createRow(rowCounter);
Cell cell = row.createCell(counter);
cell.setCellValue("test");
cell.getCellStyle().setLocked(false);
Your first snippet does not produce a document with locked cells using POI 3.9.
SXSSFWorkbook wb = new SXSSFWorkbook();
Sheet sheet = wb.createSheet("Results");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("test");
FileOutputStream fileOut = new FileOutputStream("/tmp/test.xlsx");
wb.write(fileOut);
fileOut.close();
Cells are editable in the resulting workbook, as expected.
SXSSF is the streaming POI API. It's optimized for writing huge amounts of data to XML based spreadsheets (the normal XSSF api keeps XML docs in memory and can use huge amounts of memory when building large documents). If you don't need to output large XML based documents, I'd recommend just using the XSSF api as SXSSF has several restrictions and gotchas and isn't as well documented.
See also:
SXSSF Documentation
POI Quick Start
I want to create a Excel in which only a specific column is locked(Read-only), and the rest are editable,
I am using the following approach, but that doesn't seem to work.
Create two CellStyles, one with setLocked(true) and other with setLocked(false).
Then apply the locked style for all the cells in the column which needs to be locked, and the unlocked style for all the other cells.
Protect the sheet using sheet.protectSheet("");
But when I open the created Excel in open office, I notice that all the cells are locked!
None of them are editable.
How can I achieve the above requirement?
P.S : I cant use the data validation approach.
If you do the opposite it works. Protect the whole sheet and call setLocked(false) for the cells which should be editable.
String file = "c:\\poitest.xlsx";
FileOutputStream outputStream = new FileOutputStream(file);
Workbook wb = new XSSFWorkbook();
CellStyle unlockedCellStyle = wb.createCellStyle();
unlockedCellStyle.setLocked(false);
Sheet sheet = wb.createSheet();
sheet.protectSheet("password");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("TEST");
cell.setCellStyle(unlockedCellStyle);
wb.write(outputStream);
outputStream.close();
I have a situation where I will be reading multiple lines and after some logic I need to write the lines in an Excel Sheet. I am using Apache POI for this purpose. However, the problem that I am facing is that, only the last line (from the loop) is being written to the Excel
Can someone please help me on this or provide some code snippet?
Thanks
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(2);
Cell cell = row.createCell(2);
cell.setCellValue("Use \n with word wrap on to create a new line");
//to enable newlines you need set a cell styles with wrap=true
CellStyle cs = wb.createCellStyle();
cs.setWrapText(true);
cell.setCellStyle(cs);
//increase row height to accomodate two lines of text
row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
//adjust column width to fit the content
sheet.autoSizeColumn((short)2);
FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
wb.write(fileOut);
fileOut.close();
Using newlines in cells