How to disable intermediate total using apache poi - java

How to disable intermediate total using Apache poi, I'm using apache poi for this, i want intermediate total should be disabled
Here is input in excel for understanding
Expected result
public class ApacheCreatePivotTable
{
public static void main(String[] args) throws Exception
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
//Create some data to build the pivot table on
setCellData(sheet);
// System.out.println(sheet.getRow(0).getLastCellNum());
XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference(new CellReference(0,0),new CellReference(4,sheet.getRow(0).getLastCellNum()-1)), new CellReference(0,7));
pivotTable.addRowLabel(0);
pivotTable.addRowLabel(1);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3);
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).setAxis(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STAxis.AXIS_COL);
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).addNewItems();
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).getItems().addNewItem().setT(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STItemType.DEFAULT);
pivotTable.getCTPivotTableDefinition().addNewColFields().addNewField().setX(2);
FileOutputStream fileOut = new FileOutputStream("output.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
public static void setCellData(XSSFSheet sheet)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
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("falility");
Cell cell13 = row1.createCell(2);
cell13.setCellValue("date");
Cell cell14 = row1.createCell(3);
cell14.setCellValue("cost");
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("tom");
Cell cell22 = row2.createCell(1);
cell22.setCellValue("Nal stop");
Cell cell23 = row2.createCell(2);
Calendar cal = Calendar.getInstance();
cal.set(2017,07,18);
cell23.setCellValue(sdf.format(cal.getTime()));
Cell cell24 = row2.createCell(3);
cell24.setCellValue(10);
Row row3 = sheet.createRow(2);
Cell cell31 = row3.createCell(0);
cell31.setCellValue("Ram");
Cell cell32 = row3.createCell(1);
cell32.setCellValue("Vadgao");
Cell cell33 = row3.createCell(2);
cal.set(2017,07,19);
cell33.setCellValue(sdf.format(cal.getTime()));
Cell cell34 = row3.createCell(3);
cell34.setCellValue(12);
Row row4 = sheet.createRow(3);
Cell cell41 = row4.createCell(0);
cell41.setCellValue("Terk");
Cell cell42 = row4.createCell(1);
cell42.setCellValue("Deccan");
Cell cell43 = row4.createCell(2);
cal.set(2017,07,20);
cell43.setCellValue(sdf.format(cal.getTime()));
Cell cell44 = row4.createCell(3);
cell44.setCellValue(11);
Row row5 = sheet.createRow(4);
Cell cell51 = row5.createCell(0);
cell51.setCellValue("tom");
Cell cell52 = row5.createCell(1);
cell52.setCellValue("baner");
Cell cell53 = row5.createCell(2);
cal.set(2017,07,18);
cell53.setCellValue(sdf.format(cal.getTime()));
Cell cell54 = row5.createCell(3);
cell54.setCellValue(20);
}
}
Please help me with it.

As far as I see, your main requirement is getting rid of the subtotals. This is possible using org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField.setDefaultSubtotal(false).
This was asked also here Apache POI XSSFPivotTable setDefaultSubtotal.
With your example:
import java.io.*;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class ApacheCreatePivotTable
{
public static void main(String[] args) throws Exception
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
//Create some data to build the pivot table on
setCellData(sheet);
//System.out.println(sheet.getRow(0).getLastCellNum());
XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference(new CellReference(0,0),new CellReference(4,sheet.getRow(0).getLastCellNum()-1)), new CellReference(0,7));
pivotTable.addRowLabel(0);
//set tabular layout instead of tree layout
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).setOutline(false);
/*
Apache poi adds 5 pivot field items of type "default" (<item t="default"/>) here.
This is because there are 5 rows (A1:C5) and, because they don't have a look at the data,
they are assuming max 5 different values. This is fine because Excel will rebuild its pivot cache while opening.
But if we want changing defaults, then this is not fine. Then we must know what items there are.
So we need at least as much items, as where different ones in the data, as numbered items: <item x="0"/><item x="1"/>
And we must build a cache definition which has shared elements for those items.
*/
for (int i = 0; i < 3; i++) {
//take the first 3 items as numbered items: <item x="0"/><item x="1"/>
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().getItemArray(i).unsetT();
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().getItemArray(i).setX((long)i);
}
for (int i = 4; i > 2; i--) {
//remove further items
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().removeItem(i);
}
//set new items count
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().setCount(3);
//build a cache definition which has shared elements for those items
//<sharedItems><s v="tom"/><s v="Ram"/><s v="Terk"/></sharedItems>
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldList().get(0).getSharedItems().addNewS().setV("tom");
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldList().get(0).getSharedItems().addNewS().setV("Ram");
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldList().get(0).getSharedItems().addNewS().setV("Terk");
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).setDefaultSubtotal(false);
pivotTable.addRowLabel(1);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3);
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).setAxis(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STAxis.AXIS_COL);
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).addNewItems();
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).getItems().addNewItem().setT(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STItemType.DEFAULT);
pivotTable.getCTPivotTableDefinition().addNewColFields().addNewField().setX(2);
FileOutputStream fileOut = new FileOutputStream("output.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
public static void setCellData(XSSFSheet sheet)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
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("falility");
Cell cell13 = row1.createCell(2);
cell13.setCellValue("date");
Cell cell14 = row1.createCell(3);
cell14.setCellValue("cost");
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("tom");
Cell cell22 = row2.createCell(1);
cell22.setCellValue("Nal stop");
Cell cell23 = row2.createCell(2);
Calendar cal = Calendar.getInstance();
cal.set(2017,07,18);
cell23.setCellValue(sdf.format(cal.getTime()));
Cell cell24 = row2.createCell(3);
cell24.setCellValue(10);
Row row3 = sheet.createRow(2);
Cell cell31 = row3.createCell(0);
cell31.setCellValue("Ram");
Cell cell32 = row3.createCell(1);
cell32.setCellValue("Vadgao");
Cell cell33 = row3.createCell(2);
cal.set(2017,07,19);
cell33.setCellValue(sdf.format(cal.getTime()));
Cell cell34 = row3.createCell(3);
cell34.setCellValue(12);
Row row4 = sheet.createRow(3);
Cell cell41 = row4.createCell(0);
cell41.setCellValue("Terk");
Cell cell42 = row4.createCell(1);
cell42.setCellValue("Deccan");
Cell cell43 = row4.createCell(2);
cal.set(2017,07,20);
cell43.setCellValue(sdf.format(cal.getTime()));
Cell cell44 = row4.createCell(3);
cell44.setCellValue(11);
Row row5 = sheet.createRow(4);
Cell cell51 = row5.createCell(0);
cell51.setCellValue("tom");
Cell cell52 = row5.createCell(1);
cell52.setCellValue("baner");
Cell cell53 = row5.createCell(2);
cal.set(2017,07,18);
cell53.setCellValue(sdf.format(cal.getTime()));
Cell cell54 = row5.createCell(3);
cell54.setCellValue(20);
}
}
Changings to your code are commented.
Result in Excel:

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

How to hide particular column in Pivot Table using Apache POI (Java)

while hiding column in pivot table. text above pivot table also getting removedI want to hide one column in pivot table. If I remove that column then the functionality should not get 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 So as shown in this Image I want to hide first column how can I hide.

Apache POI - is there a way to create a pivot table where the source table is a SXSSFSheet?

This is the case:
I have to use SXSSFWorkbook (Streaming version of XSSFWorkbook) to create my Excel, because I have to create a sheet with 700000/800000 rows with about 20 columns. This sheet represents the source table for my final Pivot.
SXSSFWorkbook workbook();
XSSFSheet pivotSheet = workbook.getXSSFWorkbook().createSheet("Pivot sheet");
AreaReference ar = ....:
CellReference cr = ....;
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(ar, cr); // ERROR!!
The problem is that, when I try to create this Pivot on that source, the XSSFPivotTable.createPivotTable method not work, despite AreaReference and CellReference arguments are ok.
If I use XSSFWorkbook (not streaming version) with less rows, all is ok, but I do not reach my goal!
Can someone give me a solution? Thank you very much!!!!!
Stefano
SXSSFWorkbook can be created from XSSFWorkbook.
So what I would do is creating XSSFWorkbook having a XSSFSheet with at least the headings of the data and another XSSFSheet for the pivot table. Then creating the XSSFPivotTable on this XSSFSheet but making the reference to the data sheet big enough for later data.
Then I would creating the SXSSFWorkbook from this XSSFWorkbook, getting the data sheet as SXSSFSheet and then streaming the big amount of data into the data sheet.
Complete example:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.xssf.streaming.*;
import java.util.Random;
import java.io.FileOutputStream;
class SXSSFPivotTableTest {
private static void streamCellData(Sheet sheet, int rowsCount) {
for (int r = 1; r <= rowsCount; r++) {
Row row = sheet.createRow(r);
Cell cell = row.createCell(0);
cell.setCellValue("Name " + ((r-1) % 4 + 1));
cell = row.createCell(1);
cell.setCellValue(r * new java.util.Random().nextDouble());
cell = row.createCell(2);
cell.setCellValue(r * new java.util.Random().nextDouble());
cell = row.createCell(3);
cell.setCellValue("City " + ((r-1) % 3 + 1));
}
}
public static void main(String[] args) throws Exception{
int rowsCount = 1000000;
//first create XSSFWorkbook
XSSFWorkbook wb = new XSSFWorkbook();
//create XSSFSheet with at least the headings
XSSFSheet sheet = wb.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Name");
cell = row.createCell(1);
cell.setCellValue("Value1");
cell = row.createCell(2);
cell.setCellValue("Value2");
cell = row.createCell(3);
cell.setCellValue("City");
//create XSSFSheet for pivot table
XSSFSheet pivotSheet = wb.createSheet("Pivot sheet");
//create pivot table
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(
new AreaReference(new CellReference("Sheet1!A1"),
new CellReference("Sheet1!D" + (rowsCount +1)), //make the reference big enough for later data
SpreadsheetVersion.EXCEL2007),
new CellReference("A5"));
//Configure the pivot table
//Use first column as row label
pivotTable.addRowLabel(0);
//Sum up the second column
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
//Avarage the third column
pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2);
//Add filter on forth column
pivotTable.addReportFilter(3);
//now create SXSSFWorkbook from XSSFWorkbook
SXSSFWorkbook swb = new SXSSFWorkbook(wb);
SXSSFSheet ssheet = swb.getSheet("Sheet1");
//now stream the big amount of data to build the pivot table on into Sheet1
streamCellData(ssheet, rowsCount);
swb.write(new FileOutputStream("SXSSFPivotTableTest.xlsx"));
swb.close();
swb.dispose();
}
}

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 apply bold text style for an entire row using Apache POI?

How to make an entire excel row cells bold text using Apache POI?
E.g:
Column headings should be in bold. Instead of applying style for each and every cell of heading row, how can I apply some style to an entire row?
This should work fine.
Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
Row row=sheet.getRow(0);
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);
If you do not create defaultFont all your workbook will be using the other one as default.
Please find below the easy way :
XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop((short) 6); // double lines border
style.setBorderBottom((short) 1); // single line border
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 15);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
Row row = sheet.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
cell0.setCellStyle(style);
for(int j = 0; j<=3; j++)
row.getCell(j).setCellStyle(style);
This work for me
I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilĂ  first row is bolded.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0);
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);
This worked for me
Object[][] bookData = { { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 },
{ "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 } };
String[] headers = new String[] { "HEader 1", "HEader 2", "HEader 3" };
int noOfColumns = headers.length;
int rowCount = 0;
Row rowZero = sheet.createRow(rowCount++);
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(font);
for (int col = 1; col <= noOfColumns; col++) {
Cell cell = rowZero.createCell(col);
cell.setCellValue(headers[col - 1]);
cell.setCellStyle(style);
}
A worked, completed and simple example:
package io.github.baijifeilong.excel;
import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
/**
* Created by BaiJiFeiLong#gmail.com at 2019/12/6 11:41
*/
public class ExcelBoldTextDemo {
#SneakyThrows
public static void main(String[] args) {
new XSSFWorkbook() {{
XSSFRow row = createSheet().createRow(0);
row.setRowStyle(createCellStyle());
row.getRowStyle().getFont().setBold(true);
row.createCell(0).setCellValue("Alpha");
row.createCell(1).setCellValue("Beta");
row.createCell(2).setCellValue("Gamma");
}}.write(new FileOutputStream("demo.xlsx"));
}
}
public class ExcelReader {
private XSSFWorkbook workBook;
private XSSFSheet workSheet;
public ExcelReader(String path, String sheetName){
File file = new File(path);
try {
FileInputStream inputStream = new FileInputStream(file);
workBook = new XSSFWorkbook(inputStream);
workSheet = workBook.getSheet(sheetName);
workBook.close();
}catch (Exception e){
e.printStackTrace();
}
}
public Object[][] getData(){
int rows = workSheet.getLastRowNum(); // returns number of rows
int cols = workSheet.getRow(0).getLastCellNum(); //returns number of cols
Object[][] data = new Object[rows][1];
for (int i = 0; i < rows; i++) {
Map<String,String> map = new HashMap<>();
for (int j = 0; j < cols; j++) {
//each column name is a key
XSSFCell cell = workSheet.getRow(i + 1).getCell(j);// might be null sometimes if the cell is empty
if (cell == null){
System.out.println();
}
map.put(workSheet.getRow(0).getCell(j).toString(),
// each cell under column name will be value
cell == null ? "" : cell.toString() );
}
data[i][0] = map;
}
return data;
}
}

Categories

Resources