How to auto adjust the column in excel in apache POI - java

I am creating an excel file with apache poi the excel is generated but i can not adjust the column with according to the cell values i am posting the code what i have done so far
This is how i have created the headers in excel
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
sheet.protectSheet("password");
sheet.autoSizeColumn(15);
HSSFFont hSSFFont = wb.createFont();
hSSFFont.setFontName(HSSFFont.FONT_ARIAL);
hSSFFont.setFontHeightInPoints((short) 8);
CellStyle style = wb.createCellStyle();
/* cell style for locking */
CellStyle lockedCellStyle = wb.createCellStyle();
lockedCellStyle.setLocked(true);
HSSFRow row = null;
HSSFCell cell = null;
row = sheet.createRow(0);
int headercolumnNo = 0;
//1st Column Header for Indicator
cell = row.createCell(headercolumnNo);
cell.setCellValue(new HSSFRichTextString(listOfActiveCarrierUserHeader.get(0)));
style.setWrapText(true);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFont(hSSFFont);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
cell.setCellStyle(style);
headercolumnNo = 1;
cell = row.createCell(headercolumnNo); //2nd Column Header for Firstname
cell.setCellValue(new HSSFRichTextString(listOfActiveCarrierUserHeader.get(1)));
style.setWrapText(true);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFont(hSSFFont);
cell.setCellStyle(style);
headercolumnNo = headercolumnNo + 1;
cell = row.createCell(headercolumnNo); //2nd Column Header for Firstname
cell.setCellValue(new HSSFRichTextString(listOfActiveCarrierUserHeader.get(2)));
style.setWrapText(true);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFont(hSSFFont);
cell.setCellStyle(style);
headercolumnNo = headercolumnNo + 1;
and this is how i have populated the values in that excel file
for(CarrierActiveUser carrierActiveUser : listOfCarrierUser){
int columnNo = 0;
row = sheet.createRow(j + 1);
cell = row.createCell(columnNo);
if(null != carrierActiveUser.getFistName()){
cell.setCellValue(new HSSFRichTextString(carrierActiveUser.getFistName()));
lockedCellStyle.setFont(hSSFFont);
cell.setCellStyle(lockedCellStyle);
}else{
cell.setCellValue(new HSSFRichTextString(" "));
cell.setCellStyle(lockedCellStyle);
}
columnNo = columnNo + 1;
cell = row.createCell(columnNo);
if(null != carrierActiveUser.getLastName()){
cell.setCellValue(new HSSFRichTextString(carrierActiveUser.getLastName()));
lockedCellStyle.setFont(hSSFFont);
cell.setCellStyle(lockedCellStyle);
}else{
cell.setCellValue(new HSSFRichTextString(" "));
cell.setCellStyle(lockedCellStyle);
}
columnNo = columnNo + 1;
cell = row.createCell(columnNo);
if(null != carrierActiveUser.getLastName()){
cell.setCellValue(new HSSFRichTextString(carrierActiveUser.getEmailId()));
lockedCellStyle.setFont(hSSFFont);
cell.setCellStyle(lockedCellStyle);
}else{
cell.setCellValue(new HSSFRichTextString(" "));
cell.setCellStyle(lockedCellStyle);
}
Please someone help me to adjust the columns , i am new to apache poi

You can use HSSFSheet.autoSizeColumn(columnNumber) method to align the columns perfectly.
This method adjusts the column width to fit the contents, read the doc.
After setting all cell values for all columns you can use this method, in your current code call this method after for loop.
Sample code
sheet.autoSizeColumn(1);
sheet.autoSizeColumn(2);
Note - You have to do this separately for all columns which you want to be aligned and the call to sheet.autoSizeColumn(columnNumber) should be made after populating the data into the excel. Calling before populating data will not have any effect.

Related

How to reduce code when create an cell in apache poi?

I am creating a sheet with apache poi, it have a lot of column and row name so I create a lot of code, I have a lot of code duplicate, How can I can create a function and reuse it for another?
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
try (OutputStream os = new FileOutputStream("report.xls")) {
Row row;
Cell cell;
row = sheet.createRow(0);
cell = row.createCell(0);
cell.setCellValue("Shop:");
cell = row.createCell(1);
cell.setCellValue(4);
cell = row.createCell(6);
cell.setCellValue("Export Date:");
cell = row.createCell(7);
cell.setCellValue("14.06.2019");
// -----
row = sheet.createRow(2);
cell = row.createCell(0);
cell.setCellValue("Code Supervisor:");
cell = row.createCell(1);
cell.setCellValue(4);
cell = row.createCell(6);
cell.setCellValue("Audit Date:");
cell = row.createCell(7);
cell.setCellValue("dd.MM.yyyy");
//----
row = sheet.createRow(4);
cell = row.createCell(6);
cell.setCellValue("Shop Note:");
cell = row.createCell(7);
cell.setCellValue("Note something");
wb.write(os);
}catch(Exception e) {
System.out.println(e.getMessage());
}

Apache POI Java XSSFCell DataFormat not beeing applied

currently im struggling setting a DataFormat to a specific row.
This is how my Excel Sheet looks like. Im having those 4 Columns.
Column 1 should take DataFormat Number
Column 2 & 3 should take DataFormat Date
Column 4 is ok
public static void createTableRow(Sheet sheet, List<String> EDIROWKeys, int col, CellStyle style , int lastRowNum){
if(sheet == null){
return;
}
int lastRow = lastRowNum;
int newRow = lastRow + 1;
Workbook wb = sheet.getWorkbook();
SimpleDateFormat format = new SimpleDateFormat();
CreationHelper helper = wb.getCreationHelper();
org.apache.poi.ss.usermodel.DataFormat date = wb.createDataFormat();
XSSFRow row = (XSSFRow) sheet.createRow(newRow);
if(row == null){
return;
}
int startCol = col;
for(String string : EDIROWKeys){
XSSFCell cell = row.createCell(startCol);
FOe.getFOPSessionContext().getDbContext().out().println(string);
if(style != null){
cell.setCellStyle(style);
}else {
XSSFWorkbook wbx = (XSSFWorkbook) sheet.getWorkbook();
XSSFDataFormat dataformat = wbx.createDataFormat();
XSSFCellStyle cs = wbx.createCellStyle();
if(startCol == 1){
cs.setDataFormat(dataformat.getFormat("#"));
}
cell.setCellStyle(cs);
}
cell.setCellValue(string);
startCol++;
}
return;
}
This is the Method i am using to Create my rows & Columns
https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/BuiltinFormats.html
This is the resource i was getting my DataFormats from.
I also tried applying those DataFormats with HssfDataformat to my cell - no success either.
I apperciate any helpful input :)
Solved by using setCellValue(Double);...
if(string.matches("\\d+")){
cell.setCellValue(Double.valueOf(string));
startCol++;
continue;
}
I see one possible case. If method argument style is null, new style, XSSFCellStyle cs is not applied to cell. Is cell.setCellStyle(cs) missing?

Writing to excel using Apache poi(Error)

I'm writing data into excel file using Apache Poi In Java Eclipse,Problem is when i add column aligned with each row,it override the previous column...here is the code before i add anything.
public static void main(String[] args) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("cellstyle");
XSSFRow row=spreadsheet.createRow(1);
XSSFCell cell;
row = spreadsheet.createRow((short) 4);
row.setHeight((short) 800);
cell = (XSSFCell) row.createCell((short) 5);
cell.setCellValue("Total Alerts raised");
spreadsheet.addMergedRegion(new CellRangeAddress(4,4,5,6));
row = spreadsheet.createRow(5);
cell = (XSSFCell) row.createCell(5);
cell.setCellValue("Critical");
row = spreadsheet.createRow(6);
cell = (XSSFCell) row.createCell(5);
cell.setCellValue("Warning");
row = spreadsheet.createRow(7);
cell = (XSSFCell) row.createCell(5);
cell.setCellValue("Total");
FileOutputStream out = new FileOutputStream(
new File("C:\\Users\\tshivhaser\\Desktop\\cellstyle.xlsx"));
workbook.write(out);
out.close();
System.out.println("cellstyle.xlsx written successfully");
}
I then add this piece of code...Critical,Warning and Total column becomes empty
row = spreadsheet.createRow(5);
cell = row.createCell(6);
cell.setCellValue(0);
row = spreadsheet.createRow(6);
cell = row.createCell(6);
cell.setCellValue(0);
row = spreadsheet.createRow(7);
cell = row.createCell(6);
cell.setCellValue(10);
Please help on how i can have all cells filled...

How to start on specific cell in a loop using apache poi?

I have an app that reads an excel and gets the information. This is my code that reads the information from column 0 and column 1. I want to know a way to start only on row number 34 and skip row 1 from 33.
File file = new File(inFileName);
Workbook workBook = WorkbookFactory.create(file);
Sheet sheet = workBook.getSheetAt(0);
Iterator<Row> rowIter = sheet.rowIterator();
while(rowIter.hasNext()){
Row myRow =rowIter.next();
Cell cell1 = myRow.getCell(0);
Cell cell2 = myRow.getCell(1);
...
Iterator<Cell> cellIter = myRow.cellIterator();
while(cellIter.hasNext()){
Cell myCell = cellIter.next();
}
//bd.addAnimalls(cell1.toString(),cell2.toString());
Toast.makeText(getApplicationContext(), "on inserting", Toast.LENGTH_SHORT).show();
}
You can get specific rows using sheet.getRow(rowNum).
So your code can be changed to this:
File file = new File(inFileName);
Workbook workBook = WorkbookFactory.create(file);
Sheet sheet = workBook.getSheetAt(0);
int rowCtr = 33;
Row myRow = sheet.getRow(rowCtr++);
while (myRow != null) {
Cell cell1 = myRow.getCell(0);
// rest of your loop code
myRow = sheet.getRow(rowCtr++);
}

Merge Consecutive cells in a Column having same values in excel

I have some data to be written into an excel Sheet.
i have done that part.
Now i want the consecutive cells of first column having same values to get merged.
I dont have any idea about how to merge cells by coding.
i use apache-poi
Below is my code.
HSSFWorkbook wb = new HSSFWorkbook();
String fromAddress,toAddress;
HSSFSheet sheet = wb.createSheet("Report 1");
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
short dateFormat = wb.createDataFormat().getFormat("dd-MM-yyyy HH:mm:ss");
SimpleDateFormat dateFormatter1 = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Proposal No."));
cell = row.createCell(1);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Equipment Name"));
cell = row.createCell(2);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Quantity Ordered"));
cell = row.createCell(3);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Invoice"));
cell = row.createCell(4);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Total Invoice Value"));
cell = row.createCell(5);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Quantity Dispatched"));
cell = row.createCell(6);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Balance Quantity"));
DispatchReports dispatchSummery=new DispatchReports();
if (dispatchSummery != null) {
dispatchList = dispatchSummery.dispatchSummery();
}
DispatchReports dispatchSummeryExtend=new DispatchReports();
if (dispatchSummeryExtend != null) {
dispatchListExtended = dispatchSummeryExtend.dispatchSummeryExtended();
}
int tempCount = 1;
//Data filling starts here
for (int key = 0; key < dispatchList.size(); key++) {
try {
CmaDispatchEquipmentDetails ws = new CmaDispatchEquipmentDetails();
int cellnum = 0;
HSSFRow row1 = sheet.createRow(tempCount++);
ws = (CmaDispatchEquipmentDetails) dispatchList.get(key);
HSSFCell cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getCmaId().getCmaNo()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getEquipmentname()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getQtyordered()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getInvoice()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getTotalinvoicevalue()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getQtydispatched()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getBalancedispatched()));
} catch (Exception e) {
e.printStackTrace();
tempCount--;
continue;
}
}
Please help me merge the consecutive cells of 'proposal No.' column that have same values.

Categories

Resources