I am trying to write data to excel sheet using Apache POI.I am using TestNG framerwork and eclipse IDE. Program is executing successfully without any error.But when I click refresh on my project source, excel sheet is not coming. Please tell me how will I see my generated excel sheet.
My code is as below:
public class Test {
public static void main(String args[]) {
try {
FileOutputStream fos = new FileOutputStream("User.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("worksheet");
HSSFRow row1 = worksheet.createRow((short) 0);
HSSFCell cell1 = row1.createCell((short) 0);
cell1.setCellValue("abc");
HSSFCell cell2 = row1.createCell((short) 1);
cell2.setCellValue("123");
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please check your project's root directory. It should be there by default. If you have specified the working directory in your run configuration -> arguments, you should check that folder. Besides, you can always get the complete file path in Java.
System.out.println(new File("User.xls").getAbsolutePath());
try this way to create file
FileOutputStream out =
new FileOutputStream(new File("User.xls"));
This file will be stored in your class directory folder.
Ex: (Test.java is stored in (c://Workspace//src//Test.java) , the file also will store in same path c://Workspace//src//User.xls")
Related
I am trying to write an excel file using java. I'm looking for just simply a column with one username per row right now, and then will build upon this later once I understand what is going a bit better. I get a zip file instead of the expected excel file, and it contains docProps, _rels, xl, and [Content_Types].xml. I don't understand how to open this zip file as though it is an excel file. I have not had luck finding the answer as all the tutorials I see show it to be a straight forward excel file, not a zip file. Is it a configuration I'm missing or is it to do with linux?
Here's my code, and what I end up with:
private void createExcelSheet(Assignment assignment) throws FileNotFoundException {
String excelFilePath = Configuration.DIRECTORY_ROOT+"/tests/"+assignment.getAssn_number()+"/gradebook-"+assignment.getAssn_number();
int rowNum = 0;
int col = 0;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(assignment.getAssn_number()+" Grades ");
XSSFRow row = spreadsheet.createRow(rowNum);
Cell cell;
for (User user : userService.getUsers() ) {
row = spreadsheet.createRow(rowNum);
cell = row.createCell(rowNum);
cell.setCellValue(user.getStudent_id());
rowNum++;
}
try (FileOutputStream fos = new FileOutputStream(excelFilePath)) {
workbook.write(fos);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I am using Apache POI 3.17 to create xlsx files and filling it with data from the db. The file gets created fine but when I try to open it, I get 'incompatible format' error even though when I inspect the file, I can see that it is a Microsoft spreadsheet file. I looked at here,here and here and tried all these examples but didn't help and I don't know where the problem is. Here is my file creation code:
File excelFile = new File("C:\\myFile.xlsx"); //a new file to be created
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(rowIndex);
Cell cell;
//some font and style creation
for(String eachHeader : headers) {
cell = row.createCell(cellIndex);
cell.setCellValue(eachHeader);
cell.setCellStyle(headerStyle);
cellIndex++;
}
//some more row and cell creation
try {
//finally try to write all this content into the excel file
OutputStream out = new FileOutputStream(excelFile);
workbook.write(out);
out.close();
logger.debug("Worksheet created: " + excelFile.getAbsolutePath());
}catch(Exception exc) {
logger.error("Error occured while creating or writing to the excel file: " + exc.getMessage());
}
Again, the file is created fine with some data in it as I can see that the size is not 0, but just cannot open it, why??
I recently attempted to rename my project in Eclipse using refactoring, and when I did I ran into many errors. I think I resolved all of them, but now my program is getting stuck while reading in a .xlsx file.
File file = new File("C://Users/user1/ExcelFile.xlsx");
if(!file.getName().endsWith("xlsx")) {
JOptionPane.showMessageDialog(null,
"Please select an Excel file (.xlsx)",
"Error", JOptionPane.ERROR_MESSAGE);
} else {
XSSFWorkbook workbook = null;
try {
// Find the workbook instance for XLSX file
workbook = new XSSFWorkbook(file);
} catch (IOException e) {
Logger.getLogger(
XLSXHandler.class.
getName()).log(Level.SEVERE, null, e);;
}
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = workbook.getSheetAt(0);
// reading sheet into taskList
tasks = readInTasks(mySheet);
}
The problem area seeems to be in the "workbook = new XSSFWorkbook(file);" line because in the debugger, workbook is filled with null values. In my build path, I have included the following .jar files:
poi-3.15-beta1.jar
poi-ooxml-3.15-beta1.jar
poi-ooxml-schemas-3.15-beta1.jar
xmlbeans-2.6.0.jar
commons-codec-1.10.jar
jxl.jar
stax-api-1.0.1.jar
Any ideas?
While trying to open an excel using ApachePOI I get
org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file: 'C:\Users\mdwaipay\AppData\Local\Temp\poifiles\poi-ooxml-1570030023.tmp'
I checked. No such folder is being created. I am using Apache POI version 3.6.
Any help? A similar code was running fine in a different workspace. At loss of thoughts here.
Code:
public Xls_Reader(String path) {
this.path=path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
}
catch (Exception e)
{ e.printStackTrace();
}
}
Why are you taking a perfectly good file, wrapping it in an InputStream, then asking POI to have to buffer the whole lot for you so it can do random access? Life is much better if you just pass the File to POI directly, so it can skip about as needed!
If you want to work with both XSSF (.xlsx) and HSSF (.xls), change your code to be
public Xls_Reader(String path) {
this.path = path;
try {
File f = new File(path);
workbook = WorkbookFactory.create(f);
sheet = workbook.getSheetAt(0);
} catch (Exception e) {
e.printStackTrace();
}
}
If you only want XSSF support, and/or you need full control of when the resources get closed, instead do something like
OPCPackage pkg = OPCPackage.open(path);
Workbook wb = new XSSFWorkbook(pkg);
// use the workbook
// When you no longer needed it, immediately close and release the file resources
pkg.close();
I am trying to generate Excel reports using Apache POI 3.6 (latest).
Since POI has limited support for header and footer generation (text only), I decided to start from a blank excel file with the header already prepared and fill the Excel cells using POI (cf. question 714172).
Unfortunately, when opening the workbook with POI and writing it immediately to disk (without any cell manpulation), the header seems to be lost.
Here is the code I used to test this behavior:
public final class ExcelWorkbookCreator {
public static void main(String[] args) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(new File("dump.xls"));
InputStream inputStream = ExcelWorkbookCreator.class.getResourceAsStream("report_template.xls");
HSSFWorkbook workbook = new HSSFWorkbook(inputStream, true);
workbook.write(outputStream);
} catch (Exception exception) {
throw new RuntimeException(exception);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException exception) {
// Nothing much to do
}
}
}
}
}
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = new HSSFSheet();
Header header = sheet.getHeader() //get header from workbook's sheet
header.setCenter(HSSFHeader.font("COURIER", "Normal")+ HSSFHeader.fontSize((short) 15) + "Hello world" +new Date()); // set header with desire font style
FileOutputStream fileOut = new FileOutputStream("C:\\book.xls");
workbook.write(fileOut);
The headers of the Excel file are preserved as long as those headers are supported in Excel 97-2003. For example, images are supported (I just tried it), but colored text is not.
The tricky part of this is that your Excel template file "dump.xls" must be in Excel 97-2003 format. Please note: this is not the file extension, but the actual contents of the file. The newest Excel will happily save the newest formatting in a .xls file, which POI cannot read.
To test this, save your Excel file as an .xls file. Important - If you receive a compatibility warning, then you must click the "Correct" link in the dialog to correct the Excel. Just clicking Proceed makes the Excel file invalid to POI.
Once you have a real .xls file (with compatible contents) then your code works. I just tested it myself:
public static void main(String[] args) throws Exception {
try (FileInputStream fis = new FileInputStream("./report_template.xls");
FileOutputStream fos = new FileOutputStream("./dump.xls")) {
HSSFWorkbook wb = new HSSFWorkbook(fis);
wb.write(fos);
}
}