File data may have been lost excel apache poi - java

This question has been asked before but my issue is definitely different. I ran my program on two different machines, both mac and used Microsoft Excel mac version to open the Excel file. Oddly one machine works perfectly and the other gives me a "file data may have been lost". I pulled the program from my git account and confirmed it is the most recent version and I cleared my cache in my browser, but it is still giving me the same error before displaying a blank excel worksheet.
JobOrderGenerator
public class JobOrderGenerator {
private OutputStream out;
private int sheetNumber = 0;
private HSSFWorkbook workbook;
private HSSFSheet sheet;
#Inject
HttpServletResponse response;
#Inject
GenerateTemplate generateTemplate;
public JobOrderGenerator(List<ShopOrder> shopOrder, HttpServletResponse response)
throws InvalidFormatException, IOException {
this.response = response;
createWorkBook();
createJobOrder(shopOrder);
createFile();
}
private void createWorkBook() {
workbook = new HSSFWorkbook();
}
private void createSheet(){
//String safeName = WorkbookUtil.createSafeSheetName(sheetName);
sheet = workbook.createSheet();
generatShopOrderTemplate();
}
private void generatShopOrderTemplate(){
generateTemplate = new GenerateTemplate();
generateTemplate.applyTemplate(workbook, sheet);
}
private void createJobOrder(List<ShopOrder> order) throws InvalidFormatException,
IOException {
//get current date time with Date()
Date todaysDate = new Date();
for(ShopOrder shopOrder: order){
writeToSpecificCell(1, 1, sheetNumber, shopOrder.getPo_number()); // Po Number
writeToSpecificCell(6, 3, sheetNumber, shopOrder.getPart_number()); // Part Number
LocalDate date = shopOrder.getPo_due_date();
String dateToString = date.toString();
writeToSpecificCell(5, 7, sheetNumber, dateToString); // Due_Date
writeToSpecificCell(2, 1, sheetNumber, todaysDate.toString());//todays date
writeToSpecificCell(6, 7, sheetNumber,
Integer.toString(shopOrder.getPart_quantity())); // Part Quantity
//writeToSpecificCell(1,2,sheetNumber, shopOrder.getMaterial); //Material
writeToSpecificCell(7, 3, sheetNumber, shopOrder.getPart_decription()); // Part Description
writeToSpecificCell(5,3,sheetNumber, shopOrder.getCustomer_name()); //Customer
writeToSpecificCell(10, 1, sheetNumber, shopOrder.getMachine_number()); // Machine
writeToSpecificCell(7, 7, sheetNumber, shopOrder.getMaterial_number()); // Material Number
sheetNumber++;
}
}
private void writeToSpecificCell(int rowNumber, int cellNumber, int sheetNumber,
String value) throws InvalidFormatException {
createSheet();
try {
sheet = workbook.getSheetAt(sheetNumber);
HSSFRow row = sheet.getRow(rowNumber);
HSSFCell cell = row.createCell(cellNumber);
if (cell == null) {
cell = row.createCell(cellNumber);
}
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(value);
} catch (NullPointerException ex) {
System.out.println("writeToSpecificCell class is returning null ");
ex.getStackTrace();
}
}
private void createFile(){
// Set Excel File Name
String fileName = "JobTicket.xls";
// Set HTT
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename="
+ fileName);
try {
out = response.getOutputStream();
workbook.write(out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Template Creator
#Named
public class GenerateTemplate {
public HSSFWorkbook applyTemplate(HSSFWorkbook workbook, HSSFSheet sheet) {
//total rows to create (starts at 0)
int totalRows = 26;//27 total rows
sheet.setColumnWidth(1, 4300);
sheet.setColumnWidth(8, 3000);
//create sheet rows
for(int i = 0; i < totalRows; i++) {
sheet.createRow(i);
}
//Fonts
//Bold Header Font
HSSFFont boldHeaderFont = workbook.createFont();
boldHeaderFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
boldHeaderFont.setFontName("Broadway");
boldHeaderFont.setItalic(true);
boldHeaderFont.setFontHeightInPoints((short) 16);
//Default Font
HSSFFont defaultFont = workbook.createFont();
defaultFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//Bold Font
HSSFFont boldFont = workbook.createFont();
boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//Bold blue Font
HSSFFont boldBlueFont = workbook.createFont();
boldBlueFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
boldBlueFont.setColor(HSSFColor.BLUE.index);
//Bold blue Tall Font
HSSFFont boldBlueTallFont = workbook.createFont();
boldBlueTallFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
boldBlueTallFont.setColor(HSSFColor.BLUE.index);
boldBlueTallFont.setFontHeightInPoints((short) 14);
//Styles
//Bold Header
HSSFCellStyle boldHeaderStyle = workbook.createCellStyle();
boldHeaderStyle.setFont(boldHeaderFont);
boldHeaderStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//Center
HSSFCellStyle centerStyle = workbook.createCellStyle();
centerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//Bold
HSSFCellStyle boldStyle = workbook.createCellStyle();
boldStyle.setFont(boldFont);
//Grey Background fill
HSSFCellStyle greyFillStyle = workbook.createCellStyle();
greyFillStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
greyFillStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
//Centered Bold Blue Style
HSSFCellStyle centeredBoldBlueStyle = workbook.createCellStyle();
centeredBoldBlueStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
centeredBoldBlueStyle.setFont(boldBlueFont);
//Centered Bold Blue Tall Style
HSSFCellStyle centeredBoldBlueTallStyle = workbook.createCellStyle();
centeredBoldBlueTallStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
centeredBoldBlueTallStyle.setFont(boldBlueTallFont);
//Merged Cells
//Name and Address merged
sheet.addMergedRegion(new CellRangeAddress(0,0,2,8));
sheet.addMergedRegion(new CellRangeAddress(1,1,2,8));
sheet.addMergedRegion(new CellRangeAddress(2,2,2,8));
sheet.addMergedRegion(new CellRangeAddress(3,3,2,8));
sheet.addMergedRegion(new CellRangeAddress(4,4,2,8));
//Customer merged
sheet.addMergedRegion(new CellRangeAddress(5,5,3,5));
//Part Merged
sheet.addMergedRegion(new CellRangeAddress(6,6,3,5));
//Create template cells
//column 1
sheet.createRow(0).createCell(0).setCellValue("Job No.");
sheet.createRow(1).createCell(0).setCellValue("P.O. No.");
sheet.createRow(2).createCell(0).setCellValue("Date");
HSSFRow row;
HSSFCell cell;
//Name and Address Info
row = sheet.getRow(1);
cell = row.createCell(2);
cell.setCellValue("Hillcrest Tool & Die");
cell.setCellStyle(boldHeaderStyle);
row = sheet.getRow(2);
cell = row.createCell(2);
cell.setCellValue("807 Jones Rd, Paragould AR");
cell.setCellStyle(centerStyle);
row = sheet.getRow(3);
cell = row.createCell(2);
cell.setCellValue("(870)573-6881");
cell.setCellStyle(centerStyle);
//Grey Background Cells
row = sheet.getRow(0);
cell = row.createCell(2);
cell.setCellStyle(greyFillStyle);
row = sheet.getRow(4);
cell = row.createCell(2);
cell.setCellStyle(greyFillStyle);
row = sheet.getRow(8);
cell = row.createCell(0);
cell.setCellStyle(greyFillStyle);
row = sheet.getRow(8);
cell = row.createCell(1);
cell.setCellStyle(greyFillStyle);
//Customer centered
row = sheet.getRow(5);
cell = row.createCell(3);
cell.setCellStyle(centeredBoldBlueStyle);
//part centered
row = sheet.getRow(6);
cell = row.createCell(3);
cell.setCellStyle(centeredBoldBlueTallStyle);
sheet.getRow(5).createCell(2).setCellValue("Customer");
sheet.getRow(5).createCell(6).setCellValue("Due Date");
sheet.getRow(6).createCell(2).setCellValue("Part No.");
sheet.getRow(6).createCell(6).setCellValue("Quantity");
sheet.createRow(7).createCell(0).setCellValue("PARTIAL");
sheet.getRow(7).createCell(2).setCellValue("Part Description");
sheet.getRow(7).createCell(6).setCellValue("Material");
sheet.getRow(9).createCell(3).setCellValue("Initials");
sheet.getRow(9).createCell(4).setCellValue("Date");
sheet.getRow(9).createCell(5).setCellValue("Operation");
sheet.getRow(9).createCell(6).setCellValue("Qty");
sheet.getRow(9).createCell(7).setCellValue("Total");
sheet.getRow(9).createCell(8).setCellValue("Hours");
sheet.createRow(10).createCell(0).setCellValue("Machine");
sheet.getRow(10).createCell(1).setCellValue("LASER / PLASMA");
sheet.getRow(17).createCell(1).setCellValue("BEND / MILL");
return workbook;
}
}

Change everything from HSSFWorkbook to XSSFWorkbook. Because HSSFWorkbook object creates XLS which doesn't support generating negative values and also it's old so use XSSFWorkbook which creates XLSX.

Related

Apache POI org.apache.poi.xssf.streaming.SXSSFWorkbook generating excel report with missing header names

I am using apache poi library to dynamically generate excel report. Previously I used HSSFWorkbook class to create excel sheet.when I generated an excel report with a large number of records I got out of memory error issue due to Garbage collection overload.due to this reason I switched org.apache.poi.xssf.streaming.SXSSFWorkbook and which resolved the previous outofmemory issue.
Here is my code for generating excel report.
public Workbook getReport(String yearLevels, List<User> userList, Map<Long, Date> map) {
Workbook wb = new SXSSFWorkbook (100);
try {
CellStyle cellStyle1;
CellStyle cellStyle2;
Sheet sheet;
HSSFRichTextString cellValue;
Row row;
Cell cell;
Font font1;
Font font2;
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
sheet = wb.createSheet("User Details Report");
sheet.setColumnWidth(0, 7000);
sheet.setColumnWidth(1, 4000);
sheet.setColumnWidth(2, 4000);
sheet.setColumnWidth(3, 4000);
sheet.setColumnWidth(4, 3000);
sheet.setColumnWidth(5, 9000);
font1 = wb.createFont();
font1.setFontHeightInPoints((short) 10);
font1.setFontName("Arial");
font1.setBold(true);
font2 = wb.createFont();
font2.setFontHeightInPoints((short) 10);
font2.setFontName("Arial");
cellStyle1 = wb.createCellStyle();
cellStyle1.setFont(font1);
cellStyle2 = wb.createCellStyle();
cellStyle2.setFont(font2);
int rowNumber = 0;
CellStyle cellStyle3 = wb.createCellStyle();
cellStyle3.setFont(font1);
cellStyle3.setAlignment(HorizontalAlignment.CENTER);
row = sheet.createRow(rowNumber);
int cellValueCount=0;
Cell userName = row.getCell(cellValueCount, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
userName.setCellValue("Username");
userName.setCellStyle(cellStyle3);
Cell firstName = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
firstName.setCellValue("First Name");
firstName.setCellStyle(cellStyle3);
Cell lastName = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
lastName.setCellValue("Last Name");
lastName.setCellStyle(cellStyle3);
Cell yearLevel = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
yearLevel.setCellValue("Year Level");
yearLevel.setCellStyle(cellStyle3);
Cell paidStatus = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
paidStatus.setCellValue("Student No");
paidStatus.setCellStyle(cellStyle3);
Cell dateTitleFulfilled = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
dateTitleFulfilled.setCellValue("Date Fulfilled");
dateTitleFulfilled.setCellStyle(cellStyle3);
CellStyle cellStyle4 = wb.createCellStyle();
cellStyle4.setFont(font2);
cellStyle4.setAlignment(HorizontalAlignment.CENTER);
int columnNumber = 0;
for (User user : userList) {
columnNumber = 0;
rowNumber++;
row = sheet.createRow(rowNumber);
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getPrincipalId());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getFirstName());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getLastName());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
/*cell = row.getCell(columnNumber, Row.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getStudentNumber());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;*/
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(Integer.toString(user.getYearLevel()));
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getJppFulfillmentTags());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
Date date = map.get(user.getId());
if (date != null) {
String eventDate = df1.format(date);
cellValue = new HSSFRichTextString(eventDate);
} else {
cellValue = new HSSFRichTextString("");
}
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
}
} catch (Exception e) {
logger.error("ReportService::getReport Error Report Creation ", e);
}
return wb;
}
ReportService reportService = new ReportService();
Workbook wb = reportService.getReport(yearLevelsString, userList, map);
OutputStream out = response.getOutputStream();
if (request.getParameter("exportAs") == null || !request.getParameter("exportAs").equalsIgnoreCase("xls")) {
response.setHeader("Content-Disposition", "attachment;filename=User_Report.csv");
CSVPrinter csvPrinter = reportService.writeWorkbookAsCSVToOutputStream(wb, out);
csvPrinter.flush();
csvPrinter.close();
} else {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=User_Report.xls");
wb.write(out);
out.close();
}
public CSVPrinter writeWorkbookAsCSVToOutputStream(Workbook workbook, OutputStream out) throws IOException {
CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(out), CSVFormat.DEFAULT);
try {
if (workbook != null) {
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
csvPrinter.print(cell.getStringCellValue());
}
csvPrinter.println();
}
}
} catch (Exception e) {
logger.error("ReportService::writeWorkbookAsCSVToOutputStream Error Report Creation ", e);
}
return csvPrinter;
}
After this implementation when I download excel report with more than 100 records I am getting report without header names.
but when I download excel report with less than 100 records I am getting report with cell header name without issue.
Why I the excel report is generating without header names when excel report having more than 100 records?

how to write values obtained using List and Iterator in a excel file using apache poi and selenium webdriver

Hi I need to store a list of values which I obtained from a webpage using List and Iterator using selenium webdriver, I want to store/write those values in a excel sheet
Link of the website:https://www.zigwheels.com/used-car
I have obtained a list of values under popular car models and I need to store it in a excel sheet using apache poi
Coding starts here:
WebElement li=
driver.findElement(By.xpath("//span[text()='Brand and Model']//parent::div//followingsibling::div//child::div[4]/ul"));
List<WebElement> alloptions=li.findElements(By.tagName("li"));
Iterator<WebElement> itr=alloptions.iterator();
while(itr.hasNext()) {
WebElement lii=itr.next();
String list=lii.getText();
System.out.println(list);
Create file, than sheet, then rows, and fill cells in row:
public void CreateNew_Make_BeckupFile() throws IOException
{
String filePath = "filepath.xls";
File f = new File(filePath);
if (!(f.exists() && f.isFile()))
{
Workbook workbook = new XSSFWorkbook(); // new HSSFWorkbook() for generating `.xls` file
/*
* CreationHelper helps us create instances of various things like DataFormat,
* Hyperlink, RichTextString etc, in a format (HSSF, XSSF) independent way
*/
CreationHelper createHelper = workbook.getCreationHelper();
for (int p = 0; p < listaTimova.size(); p++) {
// Create a Sheet
// Sheet sheet = workbook.createSheet("Employee");
SheetCreation (workbook, p);
}
// Write the output to a file
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
// Closing the workbook
workbook.close();
outputStream.close();
}
public void SheetCreation (Workbook workbook, int teamNumber)
{
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Sheet Name");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.BLUE.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
// Create cells
for (int i = 0; i < columns.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(columns[i]);
cell.setCellStyle(headerCellStyle);
}
headerFont.setColor(IndexedColors.BLACK.getIndex());
headerCellStyle.setFont(headerFont);
for (int u = 0; u < listaTimova.get(teamNumber).listaIgracaTima.size(); u++)
{
Row headerRow2 = sheet.createRow(u + 1);
**RowCreation(headerRow2, teamNumber, u, 0);**
}
for(int i = 0; i < columns.length; i++)
{
sheet.autoSizeColumn(i);
}
}
**public void RowCreation(Row row, int teamNumber, int playerNumber, int cellNumber)**
{
row.createCell(cellNumber, CellType.STRING).setCellValue("Any value for cell");
row.createCell(cellNumber+1, CellType.STRING).setCellValue("next cell in row value...");
}

Write XLSX file to external storage in Android

I'm trying to create and save an XLSX file into my Download folder, but even if it doesn't gives error, nothing gets saved. This is the code:
private void importIntoExcel() throws IOException {
String[] columns = { "Numero Test", "Genere", "Data di nascita", "Data del test"};
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("RiepilogoTest");
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
for (int i = 0; i < columns.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(columns[i]);
cell.setCellStyle(headerCellStyle);
}
// Create Other rows and cells with contacts data
int rowNum = 1;
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(new File(Environment.getExternalStorageDirectory().toString()+"risultatiTest.xlsx"));
workbook.write(fileOut);
fileOut.close();
}

How to hide particular column in pivot table not in sheet?

Text above pivot I want to hide one column in pivot table. If I remove that column then the functionality gets effected. How can I achieve that functionality by removing or hiding that column in pivot table?
` public class Createxlsx {
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
createPivotTable();
}
private static void createPivotTable() throws IOException, FileNotFoundException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet1 = wb.createSheet("1e");
XSSFSheet sheet = wb.createSheet("1econtent");
XSSFFont font = wb.createFont();
font.setFontHeightInPoints((short) 15);
font.setColor(IndexedColors.WHITE.getIndex());
// sheet.setTabColor(10);
/* CTColor color = CTColor.Factory.newInstance();
color.setIndexed(IndexedColors.RED.getIndex());
sheet.getCTWorksheet().getSheetPr().setTabColor(color);*/
// sheet1.setTabColor( new XSSFColor( Color.RED ) );
// sheet.setTabColor(1)
/* CTColor color = CTColor.Factory.newInstance();
color.setIndexed(IndexedColors.GREEN.getIndex());
sheet1.getCTWorksheet().getSheetPr().setTabColor(color); */
// sheet1.setTabColor(0);
//Set the tab color
// sheet.setTabColor(Color.getRed());
//Save the Excel file
//workbook.save(dataDir + "AsposeColoredTab_Out.xls");
CellStyle fontStyle = wb.createCellStyle();
fontStyle.setFont(font);
fontStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
fontStyle.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
fontStyle.setWrapText(true);
CellStyle fontStyle1 = wb.createCellStyle();
fontStyle1.setFont(font);
fontStyle1.setFillPattern(FillPatternType.SOLID_FOREGROUND);
fontStyle1.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
fontStyle1.setWrapText(true);
CellStyle fontStyle2 = wb.createCellStyle();
fontStyle2.setFont(font);
fontStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
XSSFColor color = new XSSFColor();
color.setARGBHex("fcd5b4");
fontStyle2.setFillForegroundColor(color.getIndexed());
fontStyle2.setWrapText(true);
CellStyle fontStyle3 = wb.createCellStyle();
fontStyle3.setFont(font);
fontStyle3.setFillPattern(FillPatternType.SOLID_FOREGROUND);
XSSFColor color1 = new XSSFColor();
color1.setARGBHex("fcd5b4");
fontStyle3.setFillForegroundColor(color1.getIndexed());
fontStyle3.setWrapText(true);
sheet1.setDisplayGridlines(false);
sheet1.addMergedRegion(new CellRangeAddress(4,7,0,5));
sheet1.addMergedRegion(new CellRangeAddress(0,0,0,5));
sheet1.addMergedRegion(new CellRangeAddress(1,1,1,5));
sheet1.addMergedRegion(new CellRangeAddress(2,2,1,5));
sheet1.addMergedRegion(new CellRangeAddress(3,3,0,5));
sheet1.setColumnWidth(1, 25*256);
sheet1.setColumnWidth(2, 45*256);
Row row1 = sheet1.createRow(0);
Cell cell11 = row1.createCell(0);
cell11.setCellStyle(fontStyle);
cell11.setCellValue("XXX");
Row row2 = sheet1.createRow(1);
// row2.setRowStyle(fontStyle);
//row2.setRowStyle(fontStyle2);
Cell cell21 = row2.createCell(0);
//CellStyle alignCellStyle = cell21.getCellStyle();
CellStyle headerStyle = wb.createCellStyle();
headerStyle.setAlignment(HorizontalAlignment.RIGHT);
//alignCellStyle.setAlignment(HorizontalAlignment.RIGHT);
cell21.setCellValue("Preparued for:");
cell21.setCellStyle(fontStyle2);
Cell cell22 = row2.createCell(1);
cell22.setCellValue("Rerrrrts Tests");
cell22.setCellStyle(fontStyle2);
Row row3 = sheet1.createRow(2);
// row3.setRowStyle(fontStyle2);
Cell cell31 = row3.createCell(0);
CellStyle alignCellStyle1 = cell31.getCellStyle();
alignCellStyle1.setAlignment(HorizontalAlignment.RIGHT);
cell31.setCellValue("Time Period:");
cell31.setCellStyle(fontStyle2);
Cell cell32 = row3.createCell(1);
DataFormat poiFormat = wb.createDataFormat();
CellStyle cellStyle = wb.createCellStyle();
String excelFormatPattern = DateFormatConverter.convert(Locale.US, "mm/dd/yyyy");
cellStyle.setDataFormat(poiFormat.getFormat(excelFormatPattern));
cell32.setCellValue(new Date());
cell32.setCellStyle(fontStyle2);
Row row4 = sheet1.createRow(3);
Cell cell41 = row4.createCell(0);
cell41.setCellValue("Table 1e: Confs Created ");
//row4.setRowStyle(fontStyle1);
cell41.setCellStyle(fontStyle1);
Row row5 = sheet1.createRow(4);
//row5.setRowStyle(fontStyle2);
Cell cell51 = row5.createCell(0);
cell51.setCellValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
cell51.setCellStyle(fontStyle3);
setCellData(sheet,wb);
wb.getSheet("1econtent").setSelected(false);
wb.setSheetVisibility(wb.getSheetIndex("1econtent"),SheetVisibility.VISIBLE);
AreaReference source = new AreaReference("A1:D5", SpreadsheetVersion.EXCEL2007);
CellReference position = new CellReference(10,0);
XSSFPivotTable pivotTable = sheet1.createPivotTable(source, position,wb.getSheet("1econtent"));
pivotTable.addReportFilter(2);
pivotTable.addRowLabel(0);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1,"% of value");
pivotTable.getCTPivotTableDefinition().getDataFields().getDataFieldArray(1).setShowDataAs(org.openxmlformats.schemas.spreadsheetml.x2006.main.STShowDataAs.PERCENT_OF_COL);
DataFormat dataformat = wb.createDataFormat();
short numFmtId = dataformat.getFormat("0.00%");
pivotTable.getCTPivotTableDefinition().getDataFields().getDataFieldArray(1).setNumFmtId(numFmtId);
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).setAutoShow(false);
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().getItemArray(0).unsetT();
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().getItemArray(0).setX((long)0);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(0).getSharedItems().addNewS().setV("Jane");
pivotTable.getCTPivotTableDefinition().getPageFields().getPageFieldArray(0).setItem(0);
sheet1.getRow(10);
pivotTable.getCTPivotTableDefinition().getPivotTableStyleInfo().setName("PivotStyleMedium10");
try (FileOutputStream fileOut = new FileOutputStream("ooxml-pivottablesa.xlsx")) {
wb.write(fileOut);
}
}
}
public static void setCellData(XSSFSheet sheet,XSSFWorkbook wb){
Row row1 = sheet.createRow(0);
// Create a cell and put a value in it.
Cell cell11 = row1.createCell(0);
cell11.setCellValue("Names");
Cell cell12 = row1.createCell(1);
cell12.setCellValue("Confts");
Cell cell13 = row1.createCell(2);
cell13.setCellValue("ConftsAS");
Cell cell14 = row1.createCell(3);
cell14.setCellValue("Human");
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("Jane");
Cell cell22 = row2.createCell(1);
cell22.setCellValue(10);
Cell cell23 = row2.createCell(2);
cell23.setCellValue(100);
Cell cell24 = row2.createCell(3);
cell24.setCellValue("Yes");
Row row3 = sheet.createRow(2);
Cell cell31 = row3.createCell(0);
cell31.setCellValue("Tarzan");
Cell cell32 = row3.createCell(1);
cell32.setCellValue(5);
Cell cell33 = row3.createCell(2);
cell33.setCellValue(100);
Cell cell34 = row3.createCell(3);
cell34.setCellValue("Yes");
Row row4 = sheet.createRow(3);
Cell cell41 = row4.createCell(0);
cell41.setCellValue("Terk");
Cell cell42 = row4.createCell(1);
cell42.setCellValue(10);
Cell cell43 = row4.createCell(2);
cell43.setCellValue(90);
Cell cell44 = row4.createCell(3);
cell44.setCellValue("No");
cell44.getCellStyle().setHidden(false);
Row row5 = sheet.createRow(4);
Cell cell211 = row5.createCell(0);
cell211.setCellValue("Jane");
Cell cell221 = row5.createCell(1);
cell221.setCellValue(10);
Cell cell231 = row5.createCell(2);
cell231.setCellValue(60);
Cell cell241 = row5.createCell(3);
cell241.setCellValue("No");
cell241.getCellStyle().setHidden(false);
}
}`
I want to hide one column in pivot table without effecting functionality
You can hide a column using setColumnHidden(int columnIndex, boolean hidden) where the value of columnIndex for column A is 0. e.g. sheet.setColumnHidden(1, true) will hide column B.
Another way to hide a column is by using setColumnWidth(int columnIndex, int width) e.g. sheet.setColumnWidth(1, 0) will also do the same thing as above.
I would still use the first method which is specific to this purpose.
EDIT - added the following clarification to illustrate how it is valid for pivot table:
Note that this works irrespective of whether you have normal cells or you have a pivot table e.g. in the following program, sheet.setColumnHidden(9, true) will hide the column J (which has the column label, Average).
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataConsolidateFunction;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFPivotTable;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreatePivotTable {
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
// Create some data to build the pivot table on
setCellData(sheet);
AreaReference source = new AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007);
CellReference position = new CellReference("H5");
// Create a pivot table on this sheet, with H5 as the top-left cell..
// The pivot table's data source is on the same sheet in A1:D4
XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
// Configure the pivot table
// Use first column as row label
pivotTable.addRowLabel(0);
// Sum up the second column
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
// Set the third column as filter
pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2);
// Add filter on forth column
pivotTable.addReportFilter(3);
sheet.setColumnHidden(9, true);
FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable.xlsx");
wb.write(fileOut);
}
public static void setCellData(XSSFSheet sheet) {
Row row1 = sheet.createRow(0);
// Create a cell and put a value in it.
Cell cell11 = row1.createCell(0);
cell11.setCellValue("Names");
Cell cell12 = row1.createCell(1);
cell12.setCellValue("#");
Cell cell13 = row1.createCell(2);
cell13.setCellValue("%");
Cell cell14 = row1.createCell(3);
cell14.setCellValue("Human");
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("Jane");
Cell cell22 = row2.createCell(1);
cell22.setCellValue(10);
Cell cell23 = row2.createCell(2);
cell23.setCellValue(100);
Cell cell24 = row2.createCell(3);
cell24.setCellValue("Yes");
Row row3 = sheet.createRow(2);
Cell cell31 = row3.createCell(0);
cell31.setCellValue("Tarzan");
Cell cell32 = row3.createCell(1);
cell32.setCellValue(5);
Cell cell33 = row3.createCell(2);
cell33.setCellValue(90);
Cell cell34 = row3.createCell(3);
cell34.setCellValue("Yes");
Row row4 = sheet.createRow(3);
Cell cell41 = row4.createCell(0);
cell41.setCellValue("Terk");
Cell cell42 = row4.createCell(1);
cell42.setCellValue(10);
Cell cell43 = row4.createCell(2);
cell43.setCellValue(90);
Cell cell44 = row4.createCell(3);
cell44.setCellValue("No");
}
}
Note: I have modified the program given at http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreatePivotTable.java to illustrate the solution.

set column format type as date or time using HSSFSheet

I want to set my column Mobile_Time as time / Date time type column.
I have tried
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
DAO d0 = new DAO();
Map<String, String> AllUsermap = new HashMap<String, String>();
AllUsermap = d0.colleagueMap(Integer.parseInt(request.getParameter("lid")), request.getParameter("ltype"));
String date = request.getParameter("date");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment; filename=All Employees Tracking Report [Date]:" + date + ".xls");
Workbook workbook = new HSSFWorkbook();
Font font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
CellStyle HeaderStyle = workbook.createCellStyle();
HeaderStyle.setFont(font);
for (String userK : AllUsermap.keySet()) {
String userinfo[] = userK.split("-");
String userinfoval[] = AllUsermap.get(userK).split("-");
if (userinfo.length == 2 && userinfoval.length == 3) {
Sheet sheet = workbook.createSheet(userinfoval[0]);
// header
Row row = sheet.createRow(0);
Cell serial = row.createCell(0);
serial.setCellValue("#");
serial.setCellStyle(HeaderStyle);
serial = row.createCell(1);
serial.setCellValue("LOCATION");
serial.setCellStyle(HeaderStyle);
serial = row.createCell(2);
serial.setCellValue("DISTANCE");
serial.setCellStyle(HeaderStyle);
serial = row.createCell(3);
serial.setCellValue("BATTERY");
serial.setCellStyle(HeaderStyle);
serial = row.createCell(4);
serial.setCellValue("SPEED");
serial.setCellStyle(HeaderStyle);
serial = row.createCell(5);
serial.setCellValue("GPS_ACCURACY");
serial.setCellStyle(HeaderStyle);
serial = row.createCell(6);
serial.setCellValue("STATUS");
serial.setCellStyle(HeaderStyle);
serial = row.createCell(7);
serial.setCellType(1);
serial.setCellValue("MOBILE_TIME");
serial.setCellStyle(HeaderStyle);
serial = row.createCell(8);
serial.setCellValue("SPEED");
serial.setCellStyle(HeaderStyle);
// End Header
List<DailyReport> adr = new ArrayList<DailyReport>();
adr = d0.seletspecificdailyreport(Integer.parseInt(userinfo[0]), date, userinfo[1]);
if (adr.size() > 0) {
List<DailyReportDetails> adlrd = new ArrayList<DailyReportDetails>();
adlrd = d0.seletdailyreportdetails(adr.get(0).getIdDailyReport());
int i = 1;
for (DailyReportDetails drd : adlrd) {
row = sheet.createRow(i);
Cell cell = row.createCell(0);
cell.setCellValue(i);
cell = row.createCell(1);
cell.setCellValue(drd.getLocation());
cell = row.createCell(2);
cell.setCellValue(drd.getDistance());
cell = row.createCell(3);
cell.setCellValue(drd.getBattery());
cell = row.createCell(4);
cell.setCellValue(drd.getSpeed());
cell = row.createCell(5);
cell.setCellValue(drd.getAccuracy());
cell = row.createCell(6);
cell.setCellValue(drd.getOffline() == 1 ? "ONLINE" : "OFFLINE");
cell = row.createCell(7);
cell.setCellValue(drd.getMobiletime());
cell = row.createCell(8);
cell.setCellValue(userinfoval[2]);
i++;
}
}
}
}
workbook.write(response.getOutputStream()); // Write workbook to
// response.
workbook.close();
}
The upper servelet writing xcel properly but Mobile time is not in time or date format in xcel
I also have tried to put line for mobile_time column serial .
serial = row.createCell(7);
serial.setCellType(HSSFCell.LAST_COLUMN_NUMBER);
serial.setCellValue("MOBILE_TIME");
serial.setCellStyle(HeaderStyle);
and also tried the below line at the of generating row
cell = row.createCell(7);
try {
cell.setCellValue(new SimpleDateFormat("HH:mm:ss").parse(drd.getMobiletime()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But still mobile_time column is in character format .What is the proper solution?
You can do something like this :
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(0);
// Create a cell and put a date value in it. The first cell is not styled
// as a date.
Cell cell = row.createCell(0);
cell.setCellValue(new Date());
// we style the second cell as a date (and time). It is important to
// create a new cell style from the workbook otherwise you can end up
// modifying the built in style and effecting not only this cell but other cells.
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
//you can also set date as java.util.Calendar
cell = row.createCell(2);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

Categories