Write XLSX file to external storage in Android - java

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

Related

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

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

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

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

java.lang.IllegalArgumentException: Attempting to write a row[1] in the range [0,1] that is already written to disk

While Download xlsx using apache poi version 3.15 in ubuntu it is giving me:
java.lang.IllegalArgumentException: Attempting to write a row[1] in the range [0,1] that is already written to disk at org.apache.poi.xssf.streaming.SXSSFSheet.createRow(SXSSFSheet.java:133),
at org.apache.poi.xssf.streaming.SXSSFSheet.createRow(SXSSFSheet.java:62)
String fileName = "myDownloads"+".xlsx";
String sourceFolderPath = "/home/user/sampleFile/";
FileInputStream fileInputStream = new
FileInputStream(sourceFolderPath+"SampleFile.xlsx");
XSSFWorkbook wb_template = new XSSFWorkbook(fileInputStream);
fileInputStream.close();
String destinationFolderPath = "/home/user/downloads";
File dir = new File(destinationFolderPath);
if (!dir.exists()) {
dir.mkdirs();
}
SXSSFWorkbook workbook = new SXSSFWorkbook(wb_template);
workbook.setCompressTempFiles(true);
SXSSFSheet workSheet = (SXSSFSheet) workbook.getSheetAt(0);
workSheet.setRandomAccessWindowSize(100000);
SXSSFSheet workSheet1 = (SXSSFSheet) workbook.getSheetAt(1);
workSheet1.setRandomAccessWindowSize(100000);
List<Student> studentList = studnetDao.getStudentListByName("kumar");
if(CollectionUtils.isNotEmpty(studentList)) {
Integer rowIndex = 1;
for(Student s : studentList) {
Row row = workSheet.getRow(rowIndex);
if (row == null) {
row = workSheet.createRow(rowIndex);
}
}
}
The stream mode doesn't support overriding or accessing existing rows. you're using a template to create your workbook that write the second row automatically.
To solve this, you can use simple XSSWorkbook to load the template and remove the existing ones; then switch to stream mode.
Your code will be like this:
// -- create XSSFWorkbook from the template
XSSFWorkbook xssfworkbook = new XSSFWorkbook(wb_template);
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(1);
xssfSheet.removeRow(xssfSheet.getRow(1));
// -- after removing the first row; switch to stream mode. now we can start from index=1
SXSSFWorkbook workbook = new SXSSFWorkbook(xssfworkbook);
workbook.setCompressTempFiles(true);
SXSSFSheet workSheet = (SXSSFSheet) workbook.getSheetAt(0);
workSheet.setRandomAccessWindowSize(100000);
SXSSFSheet workSheet1 = (SXSSFSheet) workbook.getSheetAt(1);
workSheet1.setRandomAccessWindowSize(100000);
List<Student> studentList = studnetDao.getStudentListByName("kumar");
if(CollectionUtils.isNotEmpty(studentList)) {
Integer rowIndex = 1;
for(Student s : studentList) {
Row row = workSheet.getRow(rowIndex);
if (row == null) {
row = workSheet.createRow(rowIndex);
}
}
}

Fill the cell in xls file, using apache-poi

Why it doesn't work? I use setFillForegroundColor and it clears the cell, rather than to fill it with a color(lime) .
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
CreationHelper createHelper = workbook.getCreationHelper();
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.LIME.getIndex());
......
label1:
for (int i=0;i<ListOfList.size();i++) {
Row row = sheet.getRow(i);
for (int j=0;j<ListOfList.get(i).size();j++) {
for (int k=0;k<List.size();k++){
if (List.get(k).equals(ListOfList.get(i).get(j)) | ListOfList.get(i).get(j).contains(List.get(k))) {
System.out.println("("+List.get(k)+") ASU <--> ("+ListOfList.get(i).get(j)+") RZS "+"Строчка: "+i+" Столбец: "+j);
row.createCell(2+j).setCellStyle(style);
}
else {}
}
}
}

How to populate an Excel sheet with the data from an arraylist using Apache POI

How to populate an Excel sheet with the data from an arraylist using Apache POI?
public String exporttoexcel(UserDetails user) throws Exception {
System.out.print("Inside serviceimpl.ExportToExcel method");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
List<UserDetails> lstUserDetail = getUserDetailList();
for (int i=0; i<lstUserDetail.size(); i++) {
UserDetails lstUserDetail1 = lstUserDetail.get(i);
String a=lstUserDetail1.getStrUserName();
System.out.print("useridddd is"+a);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue(lstUserDetail1.getStrUserId());
cell.setCellValue(lstUserDetail1.getStrUserName());
cell.setCellValue(lstUserDetail1.getStrEMail());
cell.setCellValue(lstUserDetail1.getStrUserStatus());
cell.setCellValue(lstUserDetail1.getStrUserRole());
}
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
System.out.print("file created");
return null;
}
You have created one single cell and entering all the values in a same single cell each time.
You need to take two loops. One for iterating through row and another for iterating through column. Though I have not tested... use code like below.
for(int RowNum=0; RowNum<MaxArrayLength;RowNum++){
HSSFRow row = sheet.createRow(RowNum);
for(int ColNum=0; ColNum<ArrayWidth;ColNum++){
HSSFCell cell = row.createCell(ColNum);
cell.setCellValue(ArrayList[RowNum][ColNum]);
}
}
FileOutputStream fileOut = new FileOutputStream("your file path");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet name");
try {
//creating the headers
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("name");
row.createCell(1).setCellValue("Name1");
row.createCell(2).setCellValue("name2");
//get the list which u want
List<String> list = getNamesList();
int rowNum = 1;
for (Name name : list ) {
Row row1 = sheet.createRow(rowNum++);
row1.createCell(0).setCellValue((name.get..));
}
workbook.write(fileOut);
}

Categories