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

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.

Related

Custom Data Validation to thousands of cells using apache poi

I am creating an excel sheet in Java which has more than 10k records. For a particular column, I want to set a validation to all cells in that column that it can either be of "NEW_RULE-x" type where x >= 1 (NEW_RULE-1, NEW_RULE-2,..., etc.) or "x" type (1,2,...,etc.)
So manually in excel, I figured out applying below Custom Validation to cell (let's say D3) :
"=OR(AND(LEFT(D3,9)="NEW_RULE-",MID(D3,10,1)>="1"),OR(AND(D3>=1,D3<=999999)))".
If I want to apply it to D4, then the validation formula will have D4 instead of D3. Is their a generic way to do it for entire D column, so that I don't have to apply for each cell in Java code while iterating records? Below is the code to generate a quick excel sheet with data validation at D3 cell.
String filePath = "D\\mysheet.xlsx";
File file = new File(filePath);
XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream fos;
try {
XSSFSheet sheet = workbook.createSheet();
for (int i = 0; i <= 5; i++) {
XSSFRow row = sheet.getRow(i);
if(row == null)
row = sheet.createRow(i);
XSSFCell cell=row.getCell(0);
if(cell == null)
cell = row.createCell(0, XSSFCell.CELL_TYPE_STRING);
cell.setCellValue("Keyword" +i);
cell=row.getCell(1);
if(cell == null)
cell = row.createCell(1, XSSFCell.CELL_TYPE_STRING);
cell.setCellValue("PASS" +i);
System.out.println("1");
}
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createCustomConstraint(
"=OR(AND(LEFT(D3,9)=\"NEW_RULE-\",MID(D3,10,1)>=\"1\"),OR(AND(D3>=1,D3<=999999)))");
//=OR(AND(LEFT(D3,9)="NEW_RULE-",MID(D3,10,1)>="1"),OR(AND(D3>=1,D3<=999999)))
CellRangeAddressList addressList = new CellRangeAddressList(2,2,3,3);
XSSFDataValidation dataValidation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, addressList);
sheet.addValidationData(dataValidation);
fos = new FileOutputStream(filePath);
workbook.write(fos);
fos.close();
}finally{
}
}```
At first: Do not put the equals sign = in front on formula strings when set via apache poi. The equals sign is not stored in Excel's storage. It only is visible in GUI.
And when ever formulas are used , even in conditional formatting and data validation, cell references can be relativ or absolut. For example A1 is a relativ reference while $A$1 is a absolut reference. So as you are using only relative references in your formula, the references will be adjusted to new cells in sheet. For example LEFT(D1,9)="NEW_RULE-" in cell D1 will be LEFT(D2,9)="NEW_RULE-" in cell D2 and LEFT(D3,9)="NEW_RULE-" in cell D3 and so on.
So the formula string "OR(AND(LEFT($D1,9)=\"NEW_RULE-\",MID($D1,10,1)>=\"1\"),OR(AND($D1>=1,$D1<=999999)))" can be adopted for the cells D1:D1000 and will always be correct for the current relative row in absolute column D.
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddressList;
class CreateExcelDataValidation {
public static void main(String[] args) throws Exception {
//Workbook workbook = new HSSFWorkbook(); String filePath = "./mysheet.xls";
Workbook workbook = new XSSFWorkbook(); String filePath = "./mysheet.xlsx";
Sheet sheet = workbook.createSheet();
for (int i = 0; i <= 5; i++) {
Row row = sheet.getRow(i);
if (row == null) row = sheet.createRow(i);
Cell cell = row.getCell(0);
if (cell == null) cell = row.createCell(0);
cell.setCellValue("Keyword" +i);
cell = row.getCell(1);
if (cell == null) cell = row.createCell(1);
cell.setCellValue("PASS" +i);
}
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createCustomConstraint("OR(AND(LEFT($D1,9)=\"NEW_RULE-\",MID($D1,10,1)>=\"1\"),OR(AND($D1>=1,$D1<=999999)))");
CellRangeAddressList addressList = new CellRangeAddressList(0, 1000, 3, 3);
DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
if (workbook instanceof XSSFWorkbook) validation.setShowErrorBox(true);
sheet.addValidationData(validation);
FileOutputStream out = new FileOutputStream(filePath);
workbook.write(out);
workbook.close();
out.close();
}
}

Apply style on first n columns of a row in .xls using Apache POI

I am using POI for excel creation in java and having trouble setting styles on the table created.
As the table data is huge, setting style on each and every individual cell is consuming time. And when i use rowstyle, the styling happens on those columns outside the table as well. Is there a way to apply styling on limited columns (say first n columns) of each row in an efficient way?
public XSSFWorkbook createReport(XSSFWorkbook wb, Map<String, List<ReportDto>> sheetData){
int rowIndex = 1;
int columnIndex = 0;
int index = 1;
wb.getSheetAt(0);
XSSFRow tempRow;
XSSFCell tempCell;
wb.getSheetAt(0);
for (String hexa : sheetData.keySet()) {
List<COAReportSheet2Dto> itemList = sheetData.get(hexa);
ListIterator<COAReportSheet2Dto> itemIterator = itemList.listIterator();
while (itemIterator.hasNext()) {
COAReportSheet2Dto eachItemData = itemIterator.next();
if (!eachItemData.getGeneSymbol().equals("")) {
tempRow = wb.getSheetAt(0).createRow(rowIndex++);
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(index++);
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getPosition());
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getSymbol());
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(hexa);
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getViperId);
tempCell = tempRow.createCell(columnIndex);
tempCell.setCellValue(eachItemData.getViperPole);
}
columnIndex = 0;
}
}
return wb;
}
I'm not sure how you are doing this, but you can do this:
public static XSSFWorkbook createReport(XSSFWorkbook wb, Map<String, List<COAReportSheet2Dto>> sheetData){
int rowIndex = 1;
int columnIndex = 0;
int index = 1;
wb.getSheetAt(0);
XSSFRow tempRow;
XSSFCell tempCell;
wb.getSheetAt(0);
// Create style
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
for (String hexa : sheetData.keySet()) {
List<COAReportSheet2Dto> itemList = sheetData.get(hexa);
ListIterator<COAReportSheet2Dto> itemIterator = itemList.listIterator();
while (itemIterator.hasNext()) {
COAReportSheet2Dto eachItemData = itemIterator.next();
if (!eachItemData.getGeneSymbol().equals("")) {
tempRow = wb.getSheetAt(0).createRow(rowIndex++);
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(index++);
tempCell.setCellStyle(style); // style is set only on this column
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getPosition());
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getSymbol());
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(hexa);
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getViperId());
tempCell = tempRow.createCell(columnIndex);
tempCell.setCellValue(eachItemData.getViperPole());
}
columnIndex = 0;
}
}
return wb;
}
I'm creating the CellStyle in this way:
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
Then you can set the style only in the columns you want. About the performance, remember to create the CellStyle only once. This way you can set the same CellStyle in every cell you want. If you create a new CellStyle for each Cell you create, your program can consume unnecessary memory.
Another way to do that is to use the setDefaultColumnStyle from Sheet:
Sheet sheet = wb.getSheetAt(0);
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
sheet.setDefaultColumnStyle(0, style);
sheet.setDefaultColumnStyle(1, style);

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();

setCellValue not working

i can't set the value of cell ,it works if i try this
if(1==1){
celltofill.setCellValue("test");
}
but once it enters the if condition it displays what's in syso but doesn't insert values in the cell.
any ideas about how can i solve this isssue?
here is my code:
public class testexcel {
public static void main(String[] args) throws InvalidFormatException, IOException, ParseException{
FileInputStream fis = new FileInputStream("D:\\test6.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
FileOutputStream fos=new FileOutputStream("D:\\edit6.xlsx");
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFSheet sheet2 = workbook.getSheetAt(1);
for(int i=1; i <= sheet.getLastRowNum(); i++) {
for(int i1=1;i1<sheet2.getLastRowNum();i1++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
Row row2 = sheet2.getRow(i1);
Cell cell2 = row2.getCell(0);
Cell celltofill= row.createCell(5);
Cell cellres= row2.getCell(1);
if((cell.getStringCellValue()).equals(cell2.getStringCellValue())){
System.out.println((cell.getStringCellValue())+" equals "+cell2.getStringCellValue());
celltofill.setCellType(Cell.CELL_TYPE_STRING);
System.out.println("cell filled with "+cellres.getStringCellValue());
celltofill.setCellValue(cellres.getStringCellValue());
}
}
}
workbook.write(fos);
fos.close();
}
}
row.createCell(5) does exactly what it says. It creates a new empty cell every time it is called. And you are calling it for every row in sheet2 again and again although it is a cell in sheet. So even if the criterions are not fullfilled, the new empty cell is been created already in your code.
Maybe:
...
for(int i=1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
Cell celltofill= row.getCell(5);
if (celltofill == null) celltofill = row.createCell(5);
for(int i1=1;i1<sheet2.getLastRowNum();i1++){
Row row2 = sheet2.getRow(i1);
Cell cell2 = row2.getCell(0);
Cell cellres= row2.getCell(1);
...
will be more what you want?

File data may have been lost excel apache poi

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.

Categories