Unable to write data into Excel file cell - java

I want to write a String into an existing Excel file cell using Java and apache library poi. Here is my method:
public void setSuccessMessageInExcellFile(File uploadFile, HttpServletResponse response) {
try {
FileInputStream fileInputStream = new FileInputStream(uploadFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet excelSheet = workbook.getSheetAt(0);
HSSFCell cell = excelSheet.getRow(0).getCell(0);
cell.setCellValue("Imported");
fileInputStream.close();
FileOutputStream out = new FileOutputStream(uploadFile);
workbook.write(out);
out.close();
} catch(Exception ex) {
ex.getCause().printStackTrace();
}
}
there is no error but "Imported" text is not available in my Excel file.

Be sure that your file exists, writable and has the right Excel version. After that you should change your code like that, because you are getting a NullPointerException otherwise:
public void setSuccessMessageInExcellFile(File uploadFile, HttpServletResponse response) {
try {
FileInputStream fileInputStream = new FileInputStream(uploadFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet excelSheet = workbook.getSheetAt(0);
HSSFCell cell = excelSheet.createRow(0).createCell(0);
cell.setCellValue("Imported");
fileInputStream.close();
FileOutputStream out = new FileOutputStream(uploadFile);
workbook.write(out);
out.close();
} catch(Exception ex) {
ex.getCause().printStackTrace();
}
}
And better would be putting the closables in the try as argument like that:
try(FileInputStream fileInputStream = new FileInputStream(uploadFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
FileOutputStream out = new FileOutputStream(uploadFile)) {
HSSFSheet excelSheet = workbook.getSheetAt(0);
HSSFCell cell = excelSheet.createRow(0).createCell(0);
cell.setCellValue("Imported");
workbook.write(out);
} catch(Exception ex) {
ex.getCause().printStackTrace();
}

Related

SXSSFWorkbook Cannot write data, document seems to have been closed already

I'm getting an exception while writing data into an SXSSFWorkbook file. I could do the same using XSSFWorkbook and it worked just fine.
java.io.IOException: Cannot write data, document seems to have been closed already
at org.apache.poi.ooxml.POIXMLDocument.write(POIXMLDocument.java:230)
at org.apache.poi.xssf.streaming.SXSSFWorkbook.write(SXSSFWorkbook.java:953)
at org.glassfish.jersey.message.internal.StreamingOutputProvider.writeTo(StreamingOutputProvider.java:79)
at org.glassfish.jersey.message.internal.StreamingOutputProvider.writeTo(StreamingOutputProvider.java:61)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:266)
Here is my code.
public static Response createResponseUsingStreaming() throws IOException {
SXSSFWorkbook workbook = report.generateStreamingExcelReport(100);
StreamingOutput outputStream = workbook::write;
final String contentType = "application/vnd.ms-excel";
Response.ResponseBuilder responseBuilder = Response.ok(outputStream);
responseBuilder.header("Content-Disposition", "attachment; filename=test");
responseBuilder.header("Access-Control-Expose-Headers", "Content-Disposition");
responseBuilder.header("Content-Type", contentType);
Response response = responseBuilder.build();
if (null != workbook) {
workbook.dispose();
workbook.close();
}
return response;
}
public SXSSFWorkbook generateStreamingExcelReport(int rowAccessWindowSize) {
List<List<String>> rows = createRawData();
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(rowAccessWindowSize);
createExcelSummaryPage(sxssfWorkbook);
createExcelDetailPage(rows, sxssfWorkbook);
return sxssfWorkbook;
}
OPCPackage is set when creating a new SXSSFWorkbook, wondering where this is getting set to null.
public final void write(OutputStream stream) throws IOException {
OPCPackage p = getPackage();
if(p == null) {
throw new IOException("Cannot write data, document seems to have been closed already");
}
//force all children to commit their changes into the underlying OOXML Package
// TODO Shouldn't they be committing to the new one instead?
Set<PackagePart> context = new HashSet<>();
onSave(context);
context.clear();
//save extended and custom properties
getProperties().commit();
p.save(stream);
}
If you can work with XSSFWorkbook you should be able to work with SXSSFWorkbook using your XSSFWorkbook.
Here is a simple working example:
public void createExcelFileUsingSXSSFWorkbook(XSSFWorkbook wb) {
SXSSFWorkbook wbSXSSF = new SXSSFWorkbook(wb);
try {
Path path = Files.createFile(Path.of("test.xlsx"));
try (OutputStream outputStream = Files.newOutputStream(path)) {
wbSXSSF.write(outputStream);
wbSXSSF.close();
} catch (IOException e2) {
e2.printStackTrace();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
I was able to resolve this as below
outputStream = outputStream1 -> {
sxssfWorkbook.write(outputStream1);
sxssfWorkbook.dispose();
sxssfWorkbook.close();
};
The workbook was being written into on responseBuilder.build() so I had to bake write(), dispose(), and close() into the outputstream for this to work

The method getWorkbook(FileInputStream) is undefined for the type Workbook

I'm trying to write a Selenium code with JAVA for fetching input from excel using Apache POI. Below is the code, I'm getting the error message 'The method getWorkbook(FileInputStream) is undefined for the type Workbook' for the statement Workbook wb = Workbook.getWorkbook(fs); Please help me to sort this out.
public class Main {
public static void main(String[] args) {
File file = new File("C:/Users/425413/NewWorkspace/Telecom/datafile.properties");
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Properties prop = new Properties();
//load properties file
try {
prop.load(fileInput);
} catch (IOException e) {
e.printStackTrace();
}
System.setProperty("webdriver.chrome.driver","C:\\Users\\425413\\Documents\\Raji\\chromedriver_win32-for79\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(prop.getProperty("URL"));
String FilePath = "d://filepath.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);
}
}
Try with
WorkbookFactory.create

How to download csv file using spring boot controller with contents?

I am facing the issue while downloading the csv file. I have created get api in spring boot and wanted to download the file through that api. Here is my code.
#GetMapping(value = "/citydetails/download")
public ResponseEntity<Object> getCityDetails() throws IOException {
System.out.println("Starting the rest call.");
FileWriter filewriter = null;
service = new LocalityService();
try {
List<CityDetails> details = service.getCityDetailsList();
if (details.isEmpty()) {
System.out.println("List is empty.");
}
StringBuilder fileContent = new StringBuilder("STATE,DISTRICT,CITY,VILLAGE,PIN\n");
for (CityDetails data : details)
fileContent.append(data.getStatename()).append(data.getDistrict()).append(data.getCity())
.append(data.getVillage()).append(data.getPindode());
XSSFWorkbook workbook = service.saveFileContents(details);
String filename = "C:\\Users\\" + System.getProperty("user.name") + "\\Downloads\\cityDetails.csv";
FileOutputStream out = new FileOutputStream(filename);
File file = new File("cityDetails.csv");
workbook.write(out);
out = new FileOutputStream(file);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("text/csv"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "cityDetails.csv" + "\"")
.body(file);
} catch (Exception ex) {
System.out.println("Failed to execute rest" + ex.getStackTrace() + "Locale: " + ex.getLocalizedMessage());
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), "false");
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
if (filewriter != null)
filewriter.close();
}
}
Exception:
Here i have used XSSFWorkbook to save my content to csv. Now i wanted to download the csv file through Rest api which will contain the data.I have tried multiple ways but i am getting empty file.With the above code it will save the csv file in download folder in windows machine, but i want this api to work on every system so I wanted to download the csv file with contents instead of saving it to specific location. I am facing the issue, how to resolve that?
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet=wkb.createSheet("sheet1");
HSSFRow row1=sheet.createRow(0);
HSSFCell cell=row1.createCell(0);
cell.setCellValue("table_demo");
sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));
//input Excel date
HSSFRow row2=sheet.createRow(1);
row2.createCell(0).setCellValue("name");
row2.createCell(1).setCellValue("class");
row2.createCell(2).setCellValue("score_1");
row2.createCell(3).setCellValue("score_2");
HSSFRow row3=sheet.createRow(2);
row3.createCell(0).setCellValue("Jeams");
row3.createCell(1).setCellValue("High 3");
row3.createCell(2).setCellValue(87);
row3.createCell(3).setCellValue(78);
//output Excel file
OutputStream output=response.getOutputStream();
response.reset();
response.setHeader("Content-disposition", "attachment; filename=details.xls");
response.setContentType("application/msexcel");
wkb.write(output);
output.close();
This code can get a simple excel file
//image
#GetMapping(value = "/image")
public #ResponseBody byte[] getImage() throws IOException {
InputStream in = getClass()
.getResourceAsStream("/com/baeldung/produceimage/image.jpg");
return IOUtils.toByteArray(in);
}
//normal file
#GetMapping(
value = "/get-file",
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
)
public #ResponseBody byte[] getFile() throws IOException {
InputStream in = getClass()
.getResourceAsStream("/com/baeldung/produceimage/data.txt");
return IOUtils.toByteArray(in);
}

While Writing into Excel file getting Null pointer Exception

While Trying to write into Excel file getting Null pointer Exception coming from line sheet.createRow(1).createCell(5).setCellValue("Pass");
Not getting why this error is coming :(
package com.qtpselenium.Test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.qtpselenium.util.Xls_Reader;
public class ReturnTestCaseResult {
public static void main(String[] args) {
String path =System.getProperty("user.dir") + "\\src\\com\\qtpselenium\\xls\\suiteA.xlsx";
/* Xls_Reader xlsr = new Xls_Reader(System.getProperty("user.dir") + "\\src\\com\\qtpselenium\\xls\\suiteA.xlsx");
ReportDataSetResult(xlsr, "TestCaseA1", 3, "Pass" , path);*/
ReportDataSetResult("TestCaseA1", path);
}
public static void ReportDataSetResult( String TestCaseName , String path){
System.out.println(TestCaseName +"----"+ path);
try {
FileInputStream fileinp = new FileInputStream(path);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.getSheet(TestCaseName);
sheet.createRow(1).createCell(5).setCellValue("Pass");
FileOutputStream fileout = new FileOutputStream(path);
workbook.write(fileout);
fileout.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have used the no arg constructor to create the workbook:
XSSFWorkbook workbook = new XSSFWorkbook();
which means there are no sheets in the workbook. This means your sheet variable will be null. I think you want to pass the FileInputStream fileinp into the workbook constructor so that it reads from an existing file?
XSSFWorkbook workbook = new XSSFWorkbook(fileinp);
Otherwise you will need to create a sheet called TestCaseName in the workbook before you can start adding rows to it.
Maybe, row(1) is null, you can try to create it first.

How to convert XSSFWorkbook to File

I currently have an XSSFWorkbook and would like to cast it or somehow change it to File within the Java code. Is there any way of doing so?
Use XSSFWorkbook.write(java.io.OutputStream stream) to write the content to a file.
FileOutputStream out = new FileOutputStream("yourFileName.xls");
Workbook wb = new XSSFWorkbook();
//do your stuff ...
wb.write(out);
Bellow code is used and tested.
private Response sendExcelFile(Locale locale, Optional<List<List<String>>> consumersReportData) {
XSSFWorkbook workBook = ExportToExcelUtils.prepareWorkBook(consumersReportData.get(), "data");
String DisplayFileName = "Consumers-Report-" + DateUtils.getLocalDateInString(DateUtils.now());
String fileName = "/tmp/fileName.xlsx";
// Created file object here
File file = new File(fileName);
try {
FileOutputStream outputStream = new FileOutputStream(file);
workBook.write(outputStream);
} catch (FileNotFoundException e) {
LOGGER.error("File not found : fileName {} Exception details:{} ", fileName, e);
} catch (IOException e) {
LOGGER.error("IO exception : fileName {} Exception details:{} ", fileName, e);
}
ResponseBuilder responseBuilder = Response.ok((Object) file);
responseBuilder.header("Content-Disposition", "attachment; filename=" + DisplayFileName + EXCEL_FILE_EXTENSTION);
return responseBuilder.build();
}

Categories