I have the code below, and what this does is basically get my data from my table model and put this into a spreadsheet. However upon exporting the data the data is not being kept in the order i specified when sorting my table:
This is defined as below from another method that sorts the table rows and the executes the method saveSingleTableAsExcel(); which exports the data:
.......
sorter = new TableRowSorter<>(tableR.getModel());
tableR.setRowSorter(sorter);
sortKeys = new ArrayList<>();
int columnIndexToSort = 0;
sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
sorter.sort();
saveSingleTableAsExcel();
.......
public void saveSingleTableAsExcel() throws FileNotFoundException{
Map<String,TableModel> models = new HashMap<String,TableModel>();
models.put("Sheet1", modelR);
saveTablesAsExcel(models);
}
public static void saveTablesAsExcel(Map<String,TableModel> models) throws FileNotFoundException{
HSSFWorkbook wb = new HSSFWorkbook();
for (String sheetName : models.keySet()){
createSheet(wb, models.get(sheetName), sheetName);
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HHmmss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); //2014/08/06 16:00:22
//FileOutputStream out = null;
FileOutputStream out = new FileOutputStream("C:\\Users\\tester.xls");
try {
wb.write(out);
out.close();
} catch (IOException e) {
}
}
/**
* Create a Sheet in the workbook using data from the TableModel
*
* #param wb
* #param model
* #param sheetName
*/
private static void createSheet(HSSFWorkbook wb, TableModel model, String sheetName){
Sheet sheet = wb.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
headerRow.setHeightInPoints(12.75f);
HSSFFont boldFont = wb.createFont();
boldFont.setFontHeightInPoints((short)22);
boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle headerStyle = wb.createCellStyle();
// Create the header cells
int numColumns = model.getColumnCount();
for (int col=0; col<numColumns; col++) {
Cell cell = headerRow.createCell(col);
cell.setCellValue(model.getColumnName(col));
cell.setCellStyle(headerStyle);
}
// Set the cell values
int numRows = model.getRowCount();
for (int row=0; row<numRows; row++){
Row sheetRow = sheet.createRow(row+1); // account for header row (0)
for (int col=0; col<numColumns; col++) {
Cell cell = sheetRow.createCell(col);
Object val = model.getValueAt(row, col);
if (val instanceof Number){
cell.setCellValue((double)val);
}
else if (val instanceof Boolean){
cell.setCellValue((Boolean)val);
}
else if (val instanceof String){
cell.setCellValue(((String)val));
}
else if (val instanceof Date){
cell.setCellValue((Date)val);
}
// else {
// cell.setCellValue(val.toString());
// }
}
}
}
How can i retain the same order as the model, which is being sorted by the first column (column 0)?
Is your sort method using a comparator or equals method that haven't been overwritten? That's my best guess without seeing the sort method.
Related
I am a newbie to using POI at work.Now i'm going to use POI in java to read a bar chart in the PPT.I've added several series x to it in advance,which are the column headers of the excel to which the bar graph belongs.
But i can only read the first three columns by default with the POI.In addition,once I modify the column header of the bar chart,or want to add a fourth column(thar is,add a color)to a bar chart with only three columns, the bar chart cannot be edited when I open the PPT,indicating that the node of the bar chart is damaged.
So is there a master who can help talking how to use POI to prroperly add a color to the bar chart(add a series)?
Eg: when I debug to the "
long ptCatCnt = catDataSource.getStrRef().getStrCache().getPtCount().getVal();
It show nullpointerexecption, I don't know how structure in ppt the bar-chart is.So I want know how to update the bar-chart。
The code is :
public class PPTDemo {
public void run() {
try {
SlideShow slideShow = SlideShowFactory.create(new File("./res/1.pptx"));
for (Object o : slideShow.getSlides()) {
XSLFSlide slider = (XSLFSlide) o;
// 第一页
if (slider.getSlideNumber() == 1) {
for (POIXMLDocumentPart.RelationPart part : slider.getRelationParts()) {
POIXMLDocumentPart documentPart = part.getDocumentPart();
// 是图表
if (documentPart instanceof XSLFChart) {
XSLFChart chart = (XSLFChart) documentPart;
// 查看里面的图表数据,才能知道是什么图表
CTPlotArea plot = chart.getCTChart().getPlotArea();
// 测试数据
List<SeriesData> seriesDatas = Arrays.asList(
new SeriesData("", Arrays.asList(
new NameDouble("行1", Math.random() * 100),
new NameDouble("行2", Math.random() * 100),
new NameDouble("行3", Math.random() * 100),
new NameDouble("行4", Math.random() * 100),
new NameDouble("行5", Math.random() * 100)
)),
new SeriesData("", Arrays.asList(
new NameDouble("行1", Math.random() * 100),
new NameDouble("行2", Math.random() * 100),
new NameDouble("行3", Math.random() * 100),
new NameDouble("行4", Math.random() * 100),
new NameDouble("行5", Math.random() * 100)
))
);
XSSFWorkbook workbook = chart.getWorkbook();
XSSFSheet sheet = workbook.getSheetAt(0);
// 柱状图
if (!plot.getBarChartList().isEmpty()) {
CTBarChart barChart = plot.getBarChartArray(0);
updateChartExcelV(seriesDatas, workbook, sheet);
workbook.write(chart.getPackagePart().getOutputStream());
int i = 0;
for (CTBarSer ser : barChart.getSerList()) {
updateChartCatAndNum(seriesDatas.get(i), ser.getTx(), ser.getCat(), ser.getVal());
++i;
}
}
// 饼图
else if (!plot.getPieChartList().isEmpty()) {
// 示例饼图只有一列数据
updateChartExcelV(Arrays.asList(seriesDatas.get(0)), workbook, sheet);
workbook.write(chart.getPackagePart().getOutputStream());
CTPieChart pieChart = plot.getPieChartArray(0);
int i = 0;
for (CTPieSer ser : pieChart.getSerList()) {
updateChartCatAndNum(seriesDatas.get(i), ser.getTx(), ser.getCat(), ser.getVal());
++i;
}
}
}
}
}
}
try {
try (FileOutputStream out = new FileOutputStream("./res/o1.pptx")) {
slideShow.write(out);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
}
}
/**
* 更新图表的关联 excel, 值是纵向的
*
* #param param
* #param workbook
* #param sheet
*/
protected void updateChartExcelV(List<SeriesData> seriesDatas, XSSFWorkbook workbook, XSSFSheet sheet) {
XSSFRow title = sheet.getRow(0);
for (int i = 0; i < seriesDatas.size(); i++) {
SeriesData data = seriesDatas.get(i);
if (data.name != null && !data.name.isEmpty()) {
// 系列名称,不能修改,修改后无法打开 excel
// title.getCell(i + 1).setCellValue(data.name);
}
int size = data.value.size();
for (int j = 0; j < size; j++) {
XSSFRow row = sheet.getRow(j + 1);
if (row == null) {
row = sheet.createRow(j + 1);
}
NameDouble cellValu = data.value.get(j);
XSSFCell cell = row.getCell(0);
if (cell == null) {
cell = row.createCell(0);
}
cell.setCellValue(cellValu.name);
cell = row.getCell(i + 1);
if (cell == null) {
cell = row.createCell(i + 1);
}
cell.setCellValue(cellValu.value);
}
int lastRowNum = sheet.getLastRowNum();
if (lastRowNum > size) {
for (int idx = lastRowNum; idx > size; idx--) {
sheet.removeRow(sheet.getRow(idx));
}
}
}
}
/**
* 更新 chart 的缓存数据
*
* #param data 数据
* #param serTitle 系列的标题缓存
* #param catDataSource 条目的数据缓存
* #param numDataSource 数据的缓存
*/
protected void updateChartCatAndNum(SeriesData data, CTSerTx serTitle, CTAxDataSource catDataSource,
CTNumDataSource numDataSource) {
// 更新系列标题
// serTitle.getStrRef().setF(serTitle.getStrRef().getF()); //
// serTitle.getStrRef().getStrCache().getPtArray(0).setV(data.name);
// TODO cat 也可能是 numRef
long ptCatCnt = catDataSource.getStrRef().getStrCache().getPtCount().getVal();
long ptNumCnt = numDataSource.getNumRef().getNumCache().getPtCount().getVal();
int dataSize = data.value.size();
for (int i = 0; i < dataSize; i++) {
NameDouble cellValu = data.value.get(i);
CTStrVal cat = ptCatCnt > i ? catDataSource.getStrRef().getStrCache().getPtArray(i)
: catDataSource.getStrRef().getStrCache().addNewPt();
cat.setIdx(i);
cat.setV(cellValu.name);
CTNumVal val = ptNumCnt > i ? numDataSource.getNumRef().getNumCache().getPtArray(i)
: numDataSource.getNumRef().getNumCache().addNewPt();
val.setIdx(i);
val.setV(String.format("%.2f", cellValu.value));
}
// 更新对应 excel 的range
catDataSource.getStrRef().setF(
replaceRowEnd(catDataSource.getStrRef().getF(),
ptCatCnt,
dataSize));
numDataSource.getNumRef().setF(
replaceRowEnd(numDataSource.getNumRef().getF(),
ptNumCnt,
dataSize));
// 删除多的
if (ptNumCnt > dataSize) {
for (int idx = dataSize; idx < ptNumCnt; idx++) {
catDataSource.getStrRef().getStrCache().removePt(dataSize);
numDataSource.getNumRef().getNumCache().removePt(dataSize);
}
}
// 更新个数
catDataSource.getStrRef().getStrCache().getPtCount().setVal(dataSize);
numDataSource.getNumRef().getNumCache().getPtCount().setVal(dataSize);
}
/**
* 替换 形如: Sheet1!$A$2:$A$4 的字符
*
* #param range
* #return
*/
public static String replaceRowEnd(String range, long oldSize, long newSize) {
Pattern pattern = Pattern.compile("(:\\$[A-Z]+\\$)(\\d+)");
Matcher matcher = pattern.matcher(range);
if (matcher.find()) {
long old = Long.parseLong(matcher.group(2));
return range.replaceAll("(:\\$[A-Z]+\\$)(\\d+)", "$1" + Long.toString(old - oldSize + newSize));
}
return range;
}
/**
* 一个系列的数据
*/
public static class SeriesData {
/**
* value 系列的名字
*/
public String name;
public List<NameDouble> value;
public SeriesData(java.util.List<NameDouble> value) {
this.value = value;
}
public SeriesData(String name, List<NameDouble> value) {
this.name = name;
this.value = value;
}
public SeriesData() {
}
}
/**
*
*/
public class NameDouble {
public String name;
/**
*/
public double value;
public NameDouble(String name, double value) {
this.name = name;
this.value = value;
}
#SuppressWarnings("unused")
public NameDouble() {
}
}
}
Using current apache poi 5.0.0 updating a chart in PowerPoint is possible using the new XDDF classes. That avoids using the ooxml-schemas classes (CT... classes) directly. Using CT classes directly is error prone and needs very good knowlegde about the internally XML structure of Office Open XML.
What one needs to know is that chart data is stored in an embedded Excel workbook. So while updating the data the need is always updating the data in that workbook and updating the data in the chart.
The following example is a minimal reproducible example for how to do this.
The template BarChartSample.pptx contained a bar chart having only one series an one category. It defines the chart format. It looks like so:
The code is like this:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.AreaReference;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumns;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
public class PowerPointChangeChartData {
//patched version of XSSFTable.updateHeaders, see https://stackoverflow.com/questions/55532006/renaming-headers-of-xssftable-with-apache-poi-leads-to-corrupt-xlsx-file/55539181#55539181
static void updateHeaders(XSSFTable table) {
XSSFSheet sheet = (XSSFSheet)table.getParent();
CellReference ref = table.getStartCellReference();
if (ref == null) return;
int headerRow = ref.getRow();
int firstHeaderColumn = ref.getCol();
XSSFRow row = sheet.getRow(headerRow);
DataFormatter formatter = new DataFormatter();
if (row != null /*&& row.getCTRow().validate()*/) {
int cellnum = firstHeaderColumn;
CTTableColumns ctTableColumns = table.getCTTable().getTableColumns();
if(ctTableColumns != null) {
for (CTTableColumn col : ctTableColumns.getTableColumnList()) {
XSSFCell cell = row.getCell(cellnum);
if (cell != null) {
col.setName(formatter.formatCellValue(cell));
}
cellnum++;
}
}
}
}
static void updateChart(XSLFChart chart, Object[][] data) throws Exception {
// get chart's data source which is a Excel sheet
XSSFWorkbook chartDataWorkbook = chart.getWorkbook();
String sheetName = chartDataWorkbook.getSheetName(0);
XSSFSheet chartDataSheet = chartDataWorkbook.getSheet(sheetName);
// current Office uses a table as data source
// so get that table if present
XSSFTable chartDataTable = null;
if (chartDataSheet.getTables().size() > 0) {
chartDataTable = chartDataSheet.getTables().get(0);
}
if (chart.getChartSeries().size() == 1) { // we will process only one chart data
XDDFChartData chartData = chart.getChartSeries().get(0);
if (chartData.getSeriesCount() == 1) { // we will process only templates having one series
int rMin = 1; // first row (0) is headers row
int rMax = data.length - 1;
// set new category data
XDDFCategoryDataSource category = null;
int c = 0;
for (int r = rMin; r <= rMax; r++) {
XSSFRow row = chartDataSheet.getRow(r); if (row == null) row = chartDataSheet.createRow(r);
XSSFCell cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
cell.setCellValue((String)data[r][c]); // in sheet
}
category = XDDFDataSourcesFactory.fromStringCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c)); // in chart
// series 1, is present already
c = 1;
// set new values in sheet and in chart
XDDFNumericalDataSource<Double> values = null;
for (int r = rMin; r < rMax+1; r++) {
XSSFRow row = chartDataSheet.getRow(r); if (row == null) row = chartDataSheet.createRow(r);
XSSFCell cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
cell.setCellValue((Double)data[r][c]); // in sheet
}
values = XDDFDataSourcesFactory.fromNumericCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c));
XDDFChartData.Series series1 = chartData.getSeries(0);
series1.replaceData(category, values); // in chart
// set new title in sheet and in chart
String series1Title = (String)data[0][c];
chartDataSheet.getRow(0).getCell(c).setCellValue(series1Title); // in sheet
series1.setTitle(series1Title, new CellReference(sheetName, 0, c, true, true)); // in chart
series1.plot();
//further series, all new created
int seriesCount = data[0].length - 1;
for (int s = 2; s <= seriesCount; s++) {
c++;
// set new values
for (int r = rMin; r < rMax+1; r++) {
XSSFRow row = chartDataSheet.getRow(r); if (row == null) row = chartDataSheet.createRow(r);
XSSFCell cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
cell.setCellValue((Double)data[r][c]); // in sheet
}
values = XDDFDataSourcesFactory.fromNumericCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c));
XDDFChartData.Series series = chartData.addSeries(category, values); // in chart
// set new title
String seriesTitle = (String)data[0][c];
XSSFCell cell = chartDataSheet.getRow(0).getCell(c); if (cell == null) cell = chartDataSheet.getRow(0).createCell(c);
cell.setCellValue(seriesTitle); // in sheet
series.setTitle(seriesTitle, new CellReference(sheetName, 0, c, true, true)); // in chart
series.plot();
}
// update the table if present
if (chartDataTable != null) {
CellReference topLeft = new CellReference(chartDataSheet.getRow(0).getCell(0));
CellReference bottomRight = new CellReference(chartDataSheet.getRow(rMax).getCell(c));
AreaReference tableArea = chartDataWorkbook.getCreationHelper().createAreaReference(topLeft, bottomRight);
chartDataTable.setArea(tableArea);
updateHeaders(chartDataTable);
}
}
}
}
public static void main(String[] args) throws Exception {
String filePath = "BarChartSample.pptx"; // has template bar chart
String filePathNew = "BarChartSample_New.pptx";
Object[][] data = new Object[][] { // new data 3 series, 5 categories
{"", "Amount", "Values", "Others"}, // series title
{"Jan", 321d, 456d, 222d}, // category 1
{"Feb", 543d, 567d, 111d}, // category 2
{"Mar", 432d, 123d, 333d}, // category 3
{"Apr", 210d, 234d, 444d}, // category 4
{"May", 198d, 345d, 444d} // category 5
};
XMLSlideShow slideShow = new XMLSlideShow(new FileInputStream(filePath));
XSLFChart chart = slideShow.getCharts().get(0);
updateChart(chart, data);
FileOutputStream out = new FileOutputStream(filePathNew);
slideShow.write(out);
out.close();
slideShow.close();
}
}
The result looks like so:
Hint: The code uses a patched version of XSSFTable.updateHeaders as the current version fails updating the table headers. See Renaming headers of XSSFTable with Apache Poi leads to corrupt XLSX-file.
I'm trying to write data in excel while running my tests and in Excel Test Class I have written a code to check if specific row under column is empty then write data else increment the row by 1 and then check same and write data.
From another class I'm calling ExcelTest:
ExcelTest sfName = new ExcelTest("C:\\Users\\abc\\eclipse-workspace\\dgc\\src\\com\\dg\\base\\utility\\TestData.xlsx");
sfName.setCellData("Sheet1","SingleFactor Campaign",SFCampName);
ExcelTest Class
public class ExcelTest
{
public FileInputStream fis = null;
public FileOutputStream fos = null;
public XSSFWorkbook workbook = null;
public XSSFSheet sheet = null;
public XSSFRow row = null;
public XSSFCell cell = null;
String xlFilePath;
boolean isEmptyStringCell;
public ExcelTest(String xlFilePath) throws Exception
{
this.xlFilePath = xlFilePath;
fis = new FileInputStream(xlFilePath);
workbook = new XSSFWorkbook(fis);
fis.close();
}
public void setCellData(String sheetName, String colName, int rowNum, String value)
{
try
{
int col_Num = -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++)
{
if(row.getCell(i).getStringCellValue().trim().equals(colName))
{
col_Num = i;
}
}
sheet.autoSizeColumn(col_Num);
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();
if (this.isEmptyStringCell)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
else
{
j=j+1;
}
}
/*row = sheet.getRow(rowNum - 1);
if(row==null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(col_Num);
if(cell == null)
cell = row.createCell(col_Num);
cell.setCellValue(value);*/
System.out.println("The cell value is "+cell.getStringCellValue());
fos = new FileOutputStream(xlFilePath);
workbook.write(fos);
fos.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
If we remove the block comment(mentioned above in code and add then comment to this code listed below then it will just write data in cell whichever is provided while calling the function.
In below code I'm starting a loop till max 7 rows and then checking if the cell contains data then increment or write data and once it writes then exit the loop.
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();
if (this.isEmptyStringCell)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
else
{
j=j+1;
}
}
Expected: It should write data in a row which has no cell data.
Actual: It doesn't write anything.
I've found solution for the above question and only need to change few code and now it is working as expected:
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
//it will check if cell contains no value then create cell and set value
if(cell == null)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
}
Controller Class Method
#RequestMapping(value="generics",method=RequestMethod.POST,produces="application/json",consumes="application/json")
public String generics(#RequestBody List<Object> objectlist) throws NoSuchFieldException, SecurityException, IOException
{
System.out.println("controller:"+objectlist);
return class1service.generics(objectlist);
}
Service Class Method`
public String generics(List<Object> objectlist) throws NoSuchFieldException, SecurityException, IOException
{
System.out.println("service"+objectlist);
return class1dao.generics(objectlist);
}
Method for checking the particuler entity class and Calling the method which will generate the excel sheet for that Objects
public String generics(List<?> clazz) throws IOException, NoSuchFieldException, SecurityException
{
System.out.println("generics:"+clazz);
try
{
List<Class1> ll1=new ArrayList<Class1>();
List<Class2> ll2=new ArrayList<Class2>();
List<Class3> ll3=new ArrayList<Class3>();
System.out.println("generics:"+clazz);
System.out.println("in generics for loop");
for (int i = 0; i < clazz.size(); i++)
{
System.out.println("in clazz loop");
System.out.println("in clazz loop i:"+i);
System.out.println("befor clazz.get(i)"+(clazz.get(i)));
System.out.println("clazz instanceof List<?>"+(clazz instanceof List<?>));
if (clazz instanceof List<?>)
{
List<Class1> a2= (List<Class1>) clazz.get(i);
//ArrayList<Class1> a2=(ArrayList<Class1>) clazz.get(i);
Class1 c1=new Class1();
c1.setS1Id(((Class1) a2.get(i)).getS1Id());
System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getS1Id()));
c1.setStudentName(((Class1) a2.get(i)).getStudentName());
System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getStudentName()));
c1.setStudentAge(((Class1) a2.get(i)).getStudentAge());
System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getStudentAge()));
c1.setEnglish(((Class1) a2.get(i)).getEnglish());
System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getEnglish()));
c1.setKannada(((Class1) a2.get(i)).getKannada());
System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getKannada()));
c1.setHindi(((Class1) a2.get(i)).getMathematics());
System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getMathematics()));
c1.setScience(((Class1) a2.get(i)).getScience());
System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getScience()));
c1.setSocielSience(((Class1) a2.get(i)).getSocielSience());
System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getSocielSience()));
c1.setMathematics(((Class1) a2.get(i)).getMathematics());
System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getMathematics()));
ll1.add(c1);
System.out.println("after clazz.get(i)"+(clazz.get(i)));
// ll1=(List<Class1>) a1;
System.out.println("ll1"+ll1);
listOfClass1(ll1);
}
else if(clazz instanceof List<?>) {
List<Class2> a2=(List<Class2>) clazz.get(i);
Class2 c2=new Class2();
c2.setS2Id(a2.get(i).getS2Id());
c2.setStudentName(a2.get(i).getStudentName());
c2.setStudentAge(a2.get(i).getStudentAge());
c2.setEnglish(a2.get(i).getEnglish());
c2.setKannada(a2.get(i).getKannada());
c2.setHindi(a2.get(i).getMathematics());
c2.setScience(a2.get(i).getScience());
c2.setSocielSience(a2.get(i).getSocielSience());
c2.setMathematics(a2.get(i).getMathematics());
ll2.add(c2);
System.out.println("ll2"+ll2);
listOfClass2(ll2);
}
else if (clazz instanceof Class3)
{
List<Class3> a3=(List<Class3>) clazz.get(i);
Class3 c3=new Class3();
c3.setS3Id(a3.get(i).getS3Id());
c3.setStudentName(a3.get(i).getStudentName());
c3.setStudentAge(a3.get(i).getStudentAge());
c3.setEnglish(a3.get(i).getEnglish());
c3.setKannada(a3.get(i).getKannada());
c3.setHindi(a3.get(i).getMathematics());
c3.setScience(a3.get(i).getScience());
c3.setSocielSience(a3.get(i).getSocielSience());
c3.setMathematics(a3.get(i).getMathematics());
ll3.add(c3);
System.out.println("ll3"+ll3);
listOfClass3(ll3);
}
}
return "added";
}
catch(Exception e)
{
System.out.println(e.getMessage());
return "not added";
}
}
Method for generating excel sheet for Class1 entity Objects
public void listOfClass1(List<Class1> stud1) throws IOException
{
System.out.println("listOfClass1:"+stud1);
String[] columns = {"s1Id","studentName", "studentAge", "english","kannada","science","mathematics","socielScience","hindi","total","percentage","status"};
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("class1");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
System.out.println("");
// Creating cells
for(int i = 0; i < columns.length; i++)
{
Cell cell = headerRow.createCell(i);
cell.setCellValue(columns[i]);
cell.setCellStyle(headerCellStyle);
}
int rowCount = sheet.getLastRowNum();
// FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
// CellReference cellReference = new CellReference("SUM(D2:E2:F2:G2:H2:I2)");
// Row row = sheet.getRow(cellReference.getRow());
// Cell cell = row.getCell(cellReference.getCol());
int rowNum=1;
int x=2;
for(Class1 student1:stud1)
{
Row row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(student1.getS1Id());
System.out.println(student1.getS1Id());
row.createCell(1).setCellValue(student1.getStudentName());
// CellValue cellValue = evaluator.evaluate(cell);
row.createCell(2).setCellValue(student1.getStudentAge());
row.createCell(3).setCellValue(student1.getEnglish());
row.createCell(4).setCellValue(student1.getKannada());
row.createCell(5).setCellValue(student1.getScience());
row.createCell(6).setCellValue(student1.getMathematics());
row.createCell(7).setCellValue(student1.getSocielSience());
// row.createCell(4, cellValue.getCellType());
row.createCell(8).setCellValue(student1.getHindi());
row.createCell(9).setCellFormula("SUM(D"+x+":E"+x+":F"+x+":G"+x+":H"+x+":I"+x+")");//.setCellValue(student1.getTotal());
row.createCell(10).setCellFormula("((J"+x+")*100)/600");//student1.getPercentage());
row.createCell(11).setCellValue(true);
x++;
rowNum++;
}
// Resize all columns to fit the content size
for(int i = 0; i < columns.length; i++) {
sheet.autoSizeColumn(i);
}
// Write the output to a file
///FileOutputStream fileOut = new FileOutputStream("excelone.xlsx");
String fileOut="C:/Users/Laxmi.Baragukar/Desktop/eclipse_neon/excelclass1.xlsx";
// return str;
//Base64.Encoder data=Base64.getEncoder().;
//String str=data.encodeToString(src)
//String encode=fetching(fileOut);
FileOutputStream fileOut1 = new FileOutputStream(fileOut);
String encode=fetching(fileOut);
workbook.write(fileOut1);
fileOut1.close();
workbook.close();
//return fileOut;
}
Method for generating excel sheet for Class2 entity Objects
public void listOfClass2(List<Class2> stud1) throws IOException
{
System.out.println("listOfClass2:"+stud1);
String[] columns = {"s2Id","studentName", "studentAge", "english","kannada","science","mathematics","socielScience","hindi","total","percentage","status"};
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("class1");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
System.out.println("");
// Creating cells
for(int i = 0; i < columns.length; i++)
{
Cell cell = headerRow.createCell(i);
cell.setCellValue(columns[i]);
cell.setCellStyle(headerCellStyle);
}
int rowCount = sheet.getLastRowNum();
// FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
// CellReference cellReference = new CellReference("SUM(D2:E2:F2:G2:H2:I2)");
// Row row = sheet.getRow(cellReference.getRow());
// Cell cell = row.getCell(cellReference.getCol());
int rowNum=1;
int x=2;
for(Class2 student1:stud1)
{
Row row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(student1.getS2Id());
System.out.println(student1.getS2Id());
row.createCell(1).setCellValue(student1.getStudentName());
// CellValue cellValue = evaluator.evaluate(cell);
row.createCell(2).setCellValue(student1.getStudentAge());
row.createCell(3).setCellValue(student1.getEnglish());
row.createCell(4).setCellValue(student1.getKannada());
row.createCell(5).setCellValue(student1.getScience());
row.createCell(6).setCellValue(student1.getMathematics());
row.createCell(7).setCellValue(student1.getSocielSience());
// row.createCell(4, cellValue.getCellType());
row.createCell(8).setCellValue(student1.getHindi());
row.createCell(9).setCellFormula("SUM(D"+x+":E"+x+":F"+x+":G"+x+":H"+x+":I"+x+")");//.setCellValue(student1.getTotal());
row.createCell(10).setCellFormula("((J"+x+")*100)/600");//student1.getPercentage());
row.createCell(11).setCellValue(true);
x++;
rowNum++;
}
// Resize all columns to fit the content size
for(int i = 0; i < columns.length; i++) {
sheet.autoSizeColumn(i);
}
// Write the output to a file
///FileOutputStream fileOut = new FileOutputStream("excelone.xlsx");
String fileOut="C:/Users/Laxmi.Baragukar/Desktop/eclipse_neon/excelclass2.xlsx";
// return str;
//Base64.Encoder data=Base64.getEncoder().;
//String str=data.encodeToString(src)
//String encode=fetching(fileOut);
FileOutputStream fileOut1 = new FileOutputStream(fileOut);
String encode=fetching(fileOut);
workbook.write(fileOut1);
fileOut1.close();
workbook.close();
//return fileOut;
}
Method for generating excel sheet for Class3 entity Objects
public void listOfClass3(List<Class3> stud1) throws IOException
{
System.out.println("listOfClass3:"+stud1);
/*List<Class3> class1=new ArrayList<Class3>();
for(Class3 obj:stud1){
Class3 c1=new Class3();
c1.setS3Id(obj.getS3Id());
c1.setStudentName(obj.getStudentName());
c1.setStudentAge(obj.getStudentAge());
class1.add(c1);
}*/
String[] columns = {"s3Id","studentName", "studentAge", "english","kannada","science","mathematics","socielScience","hindi","total","percentage","status"};
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("class1");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
System.out.println("");
// Creating cells
for(int i = 0; i < columns.length; i++)
{
Cell cell = headerRow.createCell(i);
cell.setCellValue(columns[i]);
cell.setCellStyle(headerCellStyle);
}
int rowCount = sheet.getLastRowNum();
// FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
// CellReference cellReference = new CellReference("SUM(D2:E2:F2:G2:H2:I2)");
// Row row = sheet.getRow(cellReference.getRow());
// Cell cell = row.getCell(cellReference.getCol());
int rowNum=1;
int x=2;
for(Class3 student1:stud1)
{
Row row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(student1.getS3Id());
System.out.println(student1.getS3Id());
row.createCell(1).setCellValue(student1.getStudentName());
// CellValue cellValue = evaluator.evaluate(cell);
row.createCell(2).setCellValue(student1.getStudentAge());
row.createCell(3).setCellValue(student1.getEnglish());
row.createCell(4).setCellValue(student1.getKannada());
row.createCell(5).setCellValue(student1.getScience());
row.createCell(6).setCellValue(student1.getMathematics());
row.createCell(7).setCellValue(student1.getSocielSience());
// row.createCell(4, cellValue.getCellType());
row.createCell(8).setCellValue(student1.getHindi());
row.createCell(9).setCellFormula("SUM(D"+x+":E"+x+":F"+x+":G"+x+":H"+x+":I"+x+")");//.setCellValue(student1.getTotal());
row.createCell(10).setCellFormula("((J"+x+")*100)/600");//student1.getPercentage());
row.createCell(11).setCellValue(true);
x++;
rowNum++;
}
// Resize all columns to fit the content size
for(int i = 0; i < columns.length; i++) {
sheet.autoSizeColumn(i);
}
// Write the output to a file
///FileOutputStream fileOut = new FileOutputStream("excelone.xlsx");
String fileOut="C:/Users/Laxmi.Baragukar/Desktop/eclipse_neon/excelclass3.xlsx";
// return str;
//Base64.Encoder data=Base64.getEncoder().;
//String str=data.encodeToString(src)
//String encode=fetching(fileOut);
FileOutputStream fileOut1 = new FileOutputStream(fileOut);
String encode=fetching(fileOut);
workbook.write(fileOut1);
fileOut1.close();
workbook.close();
//return fileOut;
}
I am pushing list of entity class objects from the postman.if i push
Class1 entity object then it will check and generate Excel sheet for
Class1 entity or if i push class2 entity object then it will check and
generate Excel sheet for Class2 entity Object.
Please update your question. It contains too much code, most of it is not relevant for the question.
Generally, you cannot cast from LinkedHashMap to List (or vice versa). What you can do is this:
public static <V, K> void main(String[] args) {
LinkedHashMap<K,V> map = new LinkedHashMap<K, V>();
List<K> keyList = new ArrayList<>(map.keySet());
List<V> valueList = new ArrayList<>(map.values());
}
(I'm not sure if that's what you are looking for. I didn't read all the code.)
I am using JAVA 8 and Apache POI 3.17. I have an Excel file and i want to keep only few lines and delete the others. But my Excel have 40K rows and deleting them one by one is quite long (nearly 30 min :/ )
So i try to change my way of doing it. Now i think it's better to only take rows that i need in the excel source and copy to another new one. But what i have tried so far is not efficient.
I have all my rows and want to keep in a List. But this not working and create me a blank excel :
public void createExcelFileFromLog (Path logRejetFilePath, Path fichierInterdits) throws IOException {
Map<Integer, Integer> mapLigneColonne = getRowAndColumnInError(logRejetFilePath);
Workbook sourceWorkbook = WorkbookFactory.create(new File(fichierInterdits.toAbsolutePath().toString()));
Sheet sourceSheet = sourceWorkbook.getSheetAt(0);
List<Row> listLignes = new ArrayList<Row>();
// get Rows from source Excel
for (Map.Entry<Integer, Integer> entry : mapLigneColonne.entrySet()) {
listLignes.add(sourceSheet.getRow(entry.getKey()-1));
}
// The new Excel
Workbook workbookToWrite = new XSSFWorkbook();
Sheet sheetToWrite = workbookToWrite.createSheet("Interdits en erreur");
// Copy Rows
Integer i = 0;
for (Row row : listLignes) {
copyRow(sheetToWrite, row, i);
i++;
}
FileOutputStream fos = new FileOutputStream(config.getDossierTemporaire() + "Interdits_en_erreur.xlsx");
workbookToWrite.write(fos);
workbookToWrite.close();
sourceWorkbook.close();
}
private static void copyRow(Sheet newSheet, Row sourceRow, int newRowNum) {
Row newRow = newSheet.createRow(newRowNum);
newRow = sourceRow;
}
EDIT : Change the method of copyRow it's better but the date have weird format and blank cells from the original row are gone.
private static void copyRow(Sheet newSheet, Row sourceRow, int newRowNum) {
Row newRow = newSheet.createRow(newRowNum);
Integer i = 0;
for (Cell cell : sourceRow) {
if(cell.getCellTypeEnum() == CellType.NUMERIC) {
newRow.createCell(i).setCellValue(cell.getDateCellValue());
} else {
newRow.createCell(i).setCellValue(cell.getStringCellValue());
}
i++;
}
}
EDIT 2 : To keep blank cell
private static void copyRow(Sheet newSheet, Row sourceRow, Integer newRowNum, Integer cellToColor) {
Row newRow = newSheet.createRow(newRowNum);
//Integer i = 0;
int lastColumn = Math.max(sourceRow.getLastCellNum(), 0);
for(int i = 0; i < lastColumn; i++) {
Cell oldCell = sourceRow.getCell(i, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if(oldCell == null) {
newRow.createCell(i).setCellValue("");
} else if (oldCell.getCellTypeEnum() == CellType.NUMERIC) {
newRow.createCell(i).setCellValue(oldCell.getDateCellValue());
} else {
newRow.createCell(i).setCellValue(oldCell.getStringCellValue());
}
}
}
I am trying to export data from a database to Excel. I have the data exported and currently being stored in an ArrayList (this can be changed). I have been able to export the data to excel but all of the values are being exported as Strings, I need them to keep their data type i.e currency/numeric.
I am using Apache POI and am having difficult with setting the data type of the fields to anything other than String. Am I missing something? Can someone please advise me on a better way of doing this? Any assistance on this would be greatly appreciated.
public static void importDataToExcel(String sheetName, ArrayList header, ArrayList data, File xlsFilename, int sheetNumber)
throws HPSFException, FileNotFoundException, IOException {
POIFSFileSystem fs = new POIFSFileSystem();
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(xlsFilename));
HSSFSheet sheet = wb.createSheet(sheetName);
int rowIdx = 0;
short cellIdx = 0;
// Header
HSSFRow hssfHeader = sheet.createRow(rowIdx);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
for (Iterator cells = header.iterator(); cells.hasNext();) {
HSSFCell hssfCell = hssfHeader.createCell(cellIdx++);
hssfCell.setCellStyle(cellStyle);
hssfCell.setCellValue((String) cells.next());
}
// Data
rowIdx = 1;
for (Iterator rows = data.iterator(); rows.hasNext();) {
ArrayList row = (ArrayList) rows.next();
HSSFRow hssfRow = (HSSFRow) sheet.createRow(rowIdx++);
cellIdx = 0;
for (Iterator cells = row.iterator(); cells.hasNext();) {
HSSFCell hssfCell = hssfRow.createCell(cellIdx++);
hssfCell.setCellValue((String) cells.next());
}
}
Logfile.log("sheetNumber = " + sheetNumber);
wb.setSheetName(sheetNumber, sheetName);
try {
FileOutputStream out = new FileOutputStream(xlsFilename);
wb.write(out);
out.close();
} catch (IOException e) {
throw new HPSFException(e.getMessage());
}
}
You need to check for the class of your cell value before you cast:
public static void importDataToExcel(String sheetName, List<String> headers, List<List<Object>> data, File xlsFilename, int sheetNumber)
throws HPSFException, FileNotFoundException, IOException {
POIFSFileSystem fs = new POIFSFileSystem();
Workbook wb;
try {
wb = WorkbookFactory.create(new FileInputStream(xlsFilename));
} catch (InvalidFormatException ex) {
throw new IOException("Invalid workbook format");
}
Sheet sheet = wb.createSheet(sheetName);
int rowIdx = 0;
int cellIdx = 0;
// Header
Row hssfHeader = sheet.createRow(rowIdx);
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
for (final String header : headers) {
Cell hssfCell = hssfHeader.createCell(cellIdx++);
hssfCell.setCellStyle(cellStyle);
hssfCell.setCellValue(header);
}
// Data
rowIdx = 1;
for (final List<Object> row : data) {
Row hssfRow = sheet.createRow(rowIdx++);
cellIdx = 0;
for (Object value : row) {
Cell hssfCell = hssfRow.createCell(cellIdx++);
if (value instanceof String) {
hssfCell.setCellValue((String) value);
} else if (value instanceof Number) {
hssfCell.setCellValue(((Number) value).doubleValue());
} else {
throw new RuntimeException("Cell value of invalid type " + value);
}
}
}
wb.setSheetName(sheetNumber, sheetName);
try {
FileOutputStream out = new FileOutputStream(xlsFilename);
wb.write(out);
out.close();
} catch (IOException e) {
throw new HPSFException(e.getMessage());
}
}
I have also added in generics - this makes the code a lot more readable. Also you need to avoid using the actual class where possible and use the interface, for example List not ArrayList and Row not HSSFRow.