I want to make a path that saved in database.
here's my code.
#RequestMapping("import_excel")
#ResponseBody
public Map<String, ? extends Object> import_excel() {
modelMap.clear();
try {
HttpSession session = req.getSession();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Export");
Row row1 = sheet.createRow((short) 3);
row1.createCell(0).setCellValue("Asset Number");
row1.createCell(1).setCellValue("Asset Barcode");
row1.createCell(2).setCellValue("Asset Name");
short i = 4;
Row row2 = sheet.createRow(i++);
row2.createCell(0).setCellValue(as.getCdas());
row2.createCell(1).setCellValue(as.getBcd());
row2.createCell(2).setCellValue(as.getNm());
FileOutputStream fileOut = new FileOutputStream(src + "/Export.xls");
wb.write(fileOut);
fileOut.close();
modelMap.put("success", true);
modelMap.put("rows", obj);
modelMap.put("count", count);
} catch (IOException ex) {
modelMap.put("success", false);
modelMap.put("msg", ex.getMessage());
}
return modelMap;
}
I want to make FileOutputStream fileOut = new FileOutputStream(src + "/Export.xls"); with the path I save in db. so If I want to change the path I just change in db.
I've tried code above but doesnt seems work.
please help me. Thanks :)
I would suggest that use it programmatically...
use
String PathTillProject = System.getProperty("user.dir");
This will give you the system path one level up to src i.e. till your project (I assume your src is just within your project directory). For example if your project name is TestProject then location or src is TestProject/src. Now you can use it like:
String PathTillProject = System.getProperty("user.dir");
FileOutputStream fileOut = new FileOutputStream(PathTillProject + "/src/Export.xls");
Related
When I execute below code it overwrite the existing file. I want to keep old file and new file too. What can be done here? Can we rename it like Test(1).xlsx, Test(2).xlsx, Test(3).xlsx like windows pattern?
File excel = new File("C:\\TEST\\Test.xlsx");
try (FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);) {
..
..
..
try (FileOutputStream outputStream = new FileOutputStream("C:\\TEST\\Output\\Test.xlsx")) {
book.write(outputStream);
}
}
You can check if the file already exists using the exists() method before you start writing to it.
If the file already exists, write to a different file.
File excel = new File(determineFileName());
try (FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);) {
...
}
with
private String determineFileName(){
String path = "C:\\TEST\\Test.xlsx";
int counter = 0;
while(new File(path).exists()){
counter++;
path = "C:\\TEST\\Test(" + counter + ").xlsx";
}
return path;
}
I have a scenario where first I update an excel column with certain values using one test case (test case 1) and then use that file for upload in the next test case (test case 2). I am able to successfully update the file and also able to browse the file for upload. the problem is that the content is not being read from the file. I just have to open the excel file created and perform the save action manually and then when I run the test (test case 2)related to uploading it works perfectly fine. I am not sure what is causing the issue. it would be of great help if someone can support this issue.
Here are the test steps
Update file column values - code snippet
public void setColValues(String fileName, String sheetName, int colIndex, List<Integer> sData) {
try {
String excelPath = System.getProperty("director to file path");
FileInputStream fis = new FileInputStream(excelPath);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sh = workbook.getSheet(sheetName);
int rowCount = sh.getLastRowNum();
logger.info(rowCount);
int index = 0;
for (int rowCounter = 2; rowCounter <= rowCount; rowCounter++) {
sh.getRow(rowCounter).getCell(colIndex).setCellValue(sData.get(index));
index++;
}
fis.close();
FileOutputStream fos = new FileOutputStream(new File(excelPath), false);
workbook.write(fos);
workbook.close();
fos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
go to a specific URL
Click the browse button and pass the file path
Click the button to upload
It might be because you are not passing a File instance to FileInputStream constructor?
You wrote:
FileInputStream fis = new FileInputStream(excelPath);
Try instead:
FileInputStream inputStream = new FileInputStream(new File(excelPath));
I am writing to an existing excel file using Java, say this is fileA. (I'm using APACHE POI for this.)
It is possible that the excel fileA is opened by someone. It is saved in a shared folder accessed by a lot of people.
I want to avoid encountering
java.io.FileNotFoundException: (The process cannot access the file
because it is being used by another process)
Because no matter if the existing excel file is opened or not, I need to save the output of my Java app.
Upon researching, I think it is impossible to close fileA (opened by some other process/user, not by my Java App) within my Java code.
What I'm doing now is to create a new excel file, say fileB if fileA is currently opened. I'm using the code below.
File file = null;
FileOutputStream out = null;
int workbookNo = 0;
do{
String append = "";
if(workbookNo != 0){
append = "_Copy" + Integer.toString(workbookNo);
}
file = new File(filePath + "ValidateLock_" + dataDate + append + ".xlsx");
try{
out = new FileOutputStream(file);
workbookNo = 0;
}catch(FileNotFoundException e){
//e.printStackTrace();
workbookNo++;
}
}while(workbookNo != 0);
However, I'm getting the error below.
org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No
valid entries or contents found, this is not a valid OOXML (Office
Open XML) file
try like this :
try {
FileInputStream file = new FileInputStream(new File("C:\\update.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
//Update the value of cell
cell = sheet.getRow(1).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(2).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(3).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
//Close the excel input file (inputstream)
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);
//Close output excel file
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is what I need to do.
1) Accept an xlsx/xls file from client.
2) Backend will receive it in the form of multipart file
3) The file will be processed and if the format of the data is invalid, that same file will be updated and the error message will be written in the side of the input of the client.
4) this modified file will be sent back to the user.
But after several attempts, I could not make my code work.
def generateErrorReport(ServletResponse response, Map messageCollections, MultipartFile file, String ext){
FileInputStream fileIn = file.getInputStream()
Workbook workbook = (ext.equalsIgnoreCase("xls")) ? new HSSFWorkbook(fileIn) : new XSSFWorkbook(fileIn)
workbook = this.getWorkbook((MultipartFile) file, ext.equalsIgnoreCase("xls"));
try {
Sheet sheet = workbook.getSheetAt(0)
Long lastCellNum = sheet.getRow(0).getLastCellNum();
for(int i=1; i<sheet.getLastRowNum(); i++){
if(messageCollections[i]!=null && messageCollections[i]!=[] ) {
Cell cell = sheet.getRow(i).getCell(lastCellNum + 1)
cell.setCellValue(messageCollections[i]);
}
}
fileIn.close()
FileOutputStream fileOut = new FileOutputStream((File) file)
workbook.write(fileOut);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response.setHeader("Content-Disposition", "Attachment;Filename=error.xlsx")
response.outputStream << fileOut
response.outputStream.flush()
fileOut.close()
}catch(Exception ex){
println ex
}
}
Now, I think a found way to do it, that is to use POITransformer. The problem is it is used when you have a template. My idea was to use the file sent by the client as template and then just simply write the error message beside the client's input. However I couldnt find a way to write it because I couldn't find a setCellData or any method same as that.
The question is, is it possible to write to a desired cell data using POITransformer? If yes, how will I do that?
So far this is what i've done. But it still not writing. Could you tell me whats wrong?
private void bla(ServletResponse response, Map messageCollections, MultipartFile file, String ext){
InputStream is = file.getInputStream();
OutputStream os = response.outputStream;
String fileName = "error";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "Attachment;Filename=${fileName}");
try {
PoiTransformer transformer = PoiTransformer.createTransformer(is, os);
org.apache.poi.ss.usermodel.Workbook workbook = transformer.getWorkbook()
Sheet sheet = workbook.getSheetAt(workbook.getActiveSheetIndex())
int lastColNum = sheet.getRow(0).getLastCellNum()
Cell cellData;
(0..sheet.getLastRowNum()) {
if (messageCollections[it]!=null && messageCollections[it]!=[]) {
cellData = sheet.getRow(it).getCell(lastColNum+1);
cellData.setCellValue(messageCollections[it].toString())
}
}
transformer.write();
} catch (IOException ex) {
println ex
// Logger.getLogger(ExcelFileHandler.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeStream(is);
closeStream(os);
}
}
Hopefully, this answer would be helpful to others.
InputStream is = file.getInputStream();
OutputStream os = response.outputStream;
String fileName = "desiredFilename." + ext
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "Attachment;Filename=${fileName}");
try {
PoiTransformer transformer = PoiTransformer.createTransformer(is, os);
org.apache.poi.ss.usermodel.Workbook workbook = transformer.getWorkbook()
Sheet sheet = workbook.getSheetAt(workbook.getActiveSheetIndex())
int lastColNum = sheet.getRow(0).getLastCellNum()
Cell cell;
cell = sheet.getRow(0).getCell(lastColNum);
if(cell==null){
cell = sheet.getRow(0).createCell(lastColNum);
}
cell.setCellType(1)
cell.setCellValue("Message")
cell.setCellStyle(getStyle(workbook, 2))
for(int it=1; it<sheet.getLastRowNum(); it++) {
if (message.get(new Long(it))!=null && message.get(new Long(it))!=[]) {
cell = sheet.getRow(it).getCell(lastColNum);
if(cell==null){
cell = sheet.getRow(it).createCell(lastColNum);
}
cell.setCellType(1)
cell.setCellValue(message.get(new Long(it)).join(', '))
cell.setCellStyle(getStyle(workbook, 1))
}
}
sheet.autoSizeColumn(lastColNum);
transformer.write();
I want to have just a single FileOutputStream that writes contents of my workbook to a file in my application, and create multiple worksheets within this excel. I am using Apache POI to read/write to my excel. I have the below method where I am doing this -
private static void writeToSpreadSheet(String test,Map<String,String> errorMap,Object object) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook()
HSSFSheet sheet = workbook.createSheet(test);
FileOutputStream fis = new FileOutputStream("output/test.xls");
//do stuff and finally write workbook contents to a file
workbook.write(fis);
if (fis != null)
fis.close();
}
The problem I am facing here is, every time I called the writeToSpreadSheet, a new file is getting created, and the existing data is getting overwritten. I want one file only, and
need new worksheeets to be added to my existing file. How do I achieve this?
I am not near my machine so I can't provide you the exact code base, but if you follow the exact steps then you could achieve the desired results.
I have assembled the code from here and there and its not going to work as is. You have to modify the code and made it work the way you wanted. I leave that part for you.
final File file = "/output/test.xls";
HSSFWorkbook workbook = null;
FileOutputStream fileOut = new FileOutputStream(file);
private static void writeToSpreadSheet(String test,
Map<String, String> errorMap, Object object) throws IOException {
// Check whether your file exist
// if not then crate a workbook
// something like below
if (!file.exists()) {
System.out.println("Creating a new workbook '" + file + "'");
workbook = new HSSFWorkbook();
} else {
// create a method to get very last sheet number something like
// following .
int sheetIndex = getLastSheetIndex();
// if you dont to go with find last sheet index idea then you can
// create your unique name may be like timestamp or so
// add the new sheet with new index
HSSFSheet sheet = workbook.createSheet("Test Sheet " + sheetIndex);
// Write your content
workbook.write(fileOut);
fileOut.close();
}
}
private static int getLastSheetIndex() {
int sheetIndex = 1;
while (workbook.getSheet("Test Sheet " + sheetIndex) != null) {
sheetIndex++;
}
return sheetIndex;
}
Currently what are you doing:
private static void writeToSpreadSheet(String test,
Map<String, String> errorMap, Object object) throws IOException {
// Creating the new workbook every time you call this method
HSSFWorkbook workbook = new HSSFWorkbook();
// Adding the same sheet to newly created workbook
HSSFSheet sheet = workbook.createSheet(test);
FileOutputStream fis = new FileOutputStream("output/test.xls");
// causing to overwrite your old workbook
workbook.write(fis);
if (fis != null)
fis.close();
}