Related
This question already has an answer here:
Creating multiple sheets using Apache poi and servlets
(1 answer)
Closed 1 year ago.
I am trying to write the data into same excel file in different sheets, below is the code I tried here only one sheet is creating and data is updating in that sheet, new sheet name is overriding on old sheet. Here I am calling call method two times with 2 different sheet name, when we call from 1st time data need to update in sheet1 and 2nd time call data need to update in sheet2 but in this code only sheet2 is creating and data updating in that.
public static void call(Map<String, String[]> dataListLMS_IPS, String sheet)
{
try {
String filePath = "C:\\Users\\PATIV25\\Downloads\\APEX UPEX.xlsx";
File theDir = new File(filePath);
String filename = theDir.toString();
FileOutputStream fileOut = new FileOutputStream(filename);
fileOut.close();
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(sheet);
XSSFRow row;
Set<String> keyid = dataListLMS_IPS.keySet();
int rowid = 0;
// writing the data into the sheets...
CellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for (String key : keyid) {
row = spreadsheet.createRow(rowid++);
String[] i = dataListLMS_IPS.get(key);
int cellid = 0;
int a = 0;
for (String obj : i) {
Cell cell = row.createCell(cellid++);
cell.setCellValue(obj);
if (rowid != 1) {
if (i[2].equals(i[6]) && i[3].equals(i[7])) {
style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
cell.setCellValue(obj);
if (a == 2 || a == 3 || a == 6 || a == 7)
cell.setCellStyle(style);
a++;
}
}
}
}
// .xlsx is the format for Excel Sheets...
// writing the workbook into the file...
FileOutputStream out = new FileOutputStream(theDir);
workbook.write(out);
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] arg) throws Exception {
Map<String, String[]> data = new LinkedHashMap<>();
data.put("A", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
data.put("v", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
call(data, "sheet1");
call(data, "sheet2");
}
The existing logic is incorrect. You need to separate the creation of file and sheets into different sections if you want to call the call method twice. Try this:
public static void call(Map<String, String[]> dataListLMS_IPS, FileOutputStream fileOut) throws IOException
{
XSSFWorkbook workbook = new XSSFWorkbook();
Set<String> keyid = dataListLMS_IPS.keySet();
int rowid = 0;
// writing the data into the sheets...
CellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for (String key : keyid) {
XSSFSheet spreadsheet = workbook.createSheet(key);
XSSFRow row;
row = spreadsheet.createRow(0);
String[] i = dataListLMS_IPS.get(key);
int cellid = 0;
int a = 0;
for (String obj : i) {
XSSFCell cell = row.createCell(cellid++);
cell.setCellValue(obj);
if (rowid != 1) {
if (i[2].equals(i[6]) && i[3].equals(i[7])) {
style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
cell.setCellValue(obj);
if (a == 2 || a == 3 || a == 6 || a == 7)
cell.setCellStyle(style);
a++;
}
}
}
}
workbook.write(fileOut);
}
public static void main(String[] arg) throws Exception {
Map<String, String[]> data = new LinkedHashMap<>();
data.put("A", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
data.put("v", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
FileOutputStream fileOut = null;
try {
String filePath = "d:\\APEX UPEX.xlsx";
File theDir = new File(filePath);
String filename = theDir.toString();
fileOut = new FileOutputStream(filename);
call(data, fileOut);
call(data, fileOut);
}
catch (Exception e)
{
e.printStackTrace();
} finally {
if (fileOut != null)
fileOut.close();
}
}
It will create 2 sheets in the same Excel file.
I want to read and write an Excel file from Java with 3 columns and N rows, printing one string in each cell. Can anyone give me simple code snippet for this? Do I need to use any external lib or does Java have built-in support for it?
I want to do the following:
for(i=0; i <rows; i++)
//read [i,col1] ,[i,col2], [i,col3]
for(i=0; i<rows; i++)
//write [i,col1], [i,col2], [i,col3]
Try the Apache POI HSSF. Here's an example on how to read an excel file:
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell((short)c);
if(cell != null) {
// Your code here
}
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}
On the documentation page you also have examples of how to write to excel files.
Apache POI can do this for you. Specifically the HSSF module. The quick guide is most useful. Here's how to do what you want - specifically create a sheet and write it out.
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
First add all these jar files in your project class path:
poi-scratchpad-3.7-20101029
poi-3.2-FINAL-20081019
poi-3.7-20101029
poi-examples-3.7-20101029
poi-ooxml-3.7-20101029
poi-ooxml-schemas-3.7-20101029
xmlbeans-2.3.0
dom4j-1.6.1
Code for writing in a excel file:
public static void main(String[] args) {
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Employee Data");
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[]{"ID", "NAME", "LASTNAME"});
data.put("2", new Object[]{1, "Amit", "Shukla"});
data.put("3", new Object[]{2, "Lokesh", "Gupta"});
data.put("4", new Object[]{3, "John", "Adwards"});
data.put("5", new Object[]{4, "Brian", "Schultz"});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
//create a row of excelsheet
Row row = sheet.createRow(rownum++);
//get object array of prerticuler key
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if (obj instanceof String)
{
cell.setCellValue((String) obj);
}
else if (obj instanceof Integer)
{
cell.setCellValue((Integer) obj);
}
}
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
workbook.write(out);
out.close();
System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
Code for reading from excel file
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You can also consider JExcelApi. I find it better designed than POI. There's a tutorial here.
There is a new easy and very cool tool (10x to Kfir): xcelite
Write:
public class User {
#Column (name="Firstname")
private String firstName;
#Column (name="Lastname")
private String lastName;
#Column
private long id;
#Column
private Date birthDate;
}
Xcelite xcelite = new Xcelite();
XceliteSheet sheet = xcelite.createSheet("users");
SheetWriter<User> writer = sheet.getBeanWriter(User.class);
List<User> users = new ArrayList<User>();
// ...fill up users
writer.write(users);
xcelite.write(new File("users_doc.xlsx"));
Read:
Xcelite xcelite = new Xcelite(new File("users_doc.xlsx"));
XceliteSheet sheet = xcelite.getSheet("users");
SheetReader<User> reader = sheet.getBeanReader(User.class);
Collection<User> users = reader.read();
For reading a xlsx file we can use Apache POI libs
Try this:
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
.csv or POI will certainly do it, but you should be aware of Andy Khan's JExcel. I think it's by far the best Java library for working with Excel there is.
A simple CSV file should suffice
String path="C:\\Book2.xlsx";
try {
File f = new File( path );
Workbook wb = WorkbookFactory.create(f);
Sheet mySheet = wb.getSheetAt(0);
Iterator<Row> rowIter = mySheet.rowIterator();
for ( Iterator<Row> rowIterator = mySheet.rowIterator() ;rowIterator.hasNext(); )
{
for ( Iterator<Cell> cellIterator = ((Row)rowIterator.next()).cellIterator() ; cellIterator.hasNext() ; )
{
System.out.println ( ( (Cell)cellIterator.next() ).toString() );
}
System.out.println( " **************************************************************** ");
}
} catch ( Exception e )
{
System.out.println( "exception" );
e.printStackTrace();
}
and make sure to have added the jars poi and poi-ooxml (org.apache.poi) to your project
For reading data from .xlsx workbooks we need to use XSSFworkbook classes.
XSSFWorkbook xlsxBook = new XSSFWorkbook(fis);
XSSFSheet sheet = xlsxBook.getSheetAt(0); etc.
We need to use Apache-poi 3.9 # http://poi.apache.org/
For detailed info with example visit
: http://java-recent.blogspot.in
Sure , you will find the code below useful and easy to read and write. This is a util class which you can use in your main method and then you are good to use all methods below.
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
public void setExcelFile(File Path, String SheetName) throws Exception
try {
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {
try {
Row = ExcelWSheet.createRow(RowNum - 1);
Cell = Row.createCell(ColNum - 1);
Cell.setCellValue(Result);
FileOutputStream fileOut = new FileOutputStream(Path);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
using spring apache poi repo
if (fileName.endsWith(".xls")) {
File myFile = new File("file location" + fileName);
FileInputStream fis = new FileInputStream(myFile);
org.apache.poi.ss.usermodel.Workbook workbook = null;
try {
workbook = WorkbookFactory.create(fis);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue());
break;
}
System.out.print(" - ");
}
System.out.println();
}
}
I edited the most voted one a little cuz it didn't count blanks columns or rows well not totally, so here is my code i tested it and now can get any cell in any part of an excel file. also now u can have blanks columns between filled column and it will read them
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
int cblacks=0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i <= 10 || i <= rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp >= cols) cols = tmp;else{rows++;cblacks++;}
}
cols++;
}
cols=cols+cblacks;
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell(c);
if(cell != null) {
System.out.print(cell+"\n");//Your Code here
}
}
}
}} catch(Exception ioe) {
ioe.printStackTrace();}
If column number are varing you can use this
package com.org.tests;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelSimpleTest
{
String path;
public FileInputStream fis = null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row =null;
private XSSFCell cell = null;
public ExcelSimpleTest() throws IOException
{
path = System.getProperty("user.dir")+"\\resources\\Book1.xlsx";
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
}
public void ExelWorks()
{
int index = workbook.getSheetIndex("Sheet1");
sheet = workbook.getSheetAt(index);
int rownumber=sheet.getLastRowNum()+1;
for (int i=1; i<rownumber; i++ )
{
row = sheet.getRow(i);
int colnumber = row.getLastCellNum();
for (int j=0; j<colnumber; j++ )
{
cell = row.getCell(j);
System.out.println(cell.getStringCellValue());
}
}
}
public static void main(String[] args) throws IOException
{
ExcelSimpleTest excelwork = new ExcelSimpleTest();
excelwork.ExelWorks();
}
}
The corresponding mavendependency can be found here
Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.
Import data
try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
rowStream
// skip the header row that contains the column names
.skip(1)
.forEach(row -> {
System.out.println(
"row n°" + row.rowIndex()
+ " column 'User login' value : " + row.cell("User login").asString()
+ " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
);
});
}
Export data
Windmill
.export(Arrays.asList(bean1, bean2, bean3))
.withHeaderMapping(
new ExportHeaderMapping<Bean>()
.add("Name", Bean::getName)
.add("User login", bean -> bean.getUser().getLogin())
)
.asExcel()
.writeTo(new FileOutputStream("Export.xlsx"));
You need Apache POI library and this code below should help you
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
//*************************************************************
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//*************************************************************
public class AdvUse {
private static Workbook wb ;
private static Sheet sh ;
private static FileInputStream fis ;
private static FileOutputStream fos ;
private static Row row ;
private static Cell cell ;
private static String ExcelPath ;
//*************************************************************
public static void setEcxelFile(String ExcelPath, String SheetName) throws Exception {
try {
File f= new File(ExcelPath);
if(!f.exists()){
f.createNewFile();
System.out.println("File not Found so created");
}
fis = new FileInputStream("./testData.xlsx");
wb = WorkbookFactory.create(fis);
sh = wb.getSheet("SheetName");
if(sh == null){
sh = wb.getSheet(SheetName);
}
}catch(Exception e)
{System.out.println(e.getMessage());
}
}
//*************************************************************
public static void setCellData(String text , int rowno , int colno){
try{
row = sh.getRow(rowno);
if(row == null){
row = sh.createRow(rowno);
}
cell = row.getCell(colno);
if(cell!=null){
cell.setCellValue(text);
}
else{
cell = row.createCell(colno);
cell.setCellValue(text);
}
fos = new FileOutputStream(ExcelPath);
wb.write(fos);
fos.flush();
fos.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
//*************************************************************
public static String getCellData(int rowno , int colno){
try{
cell = sh.getRow(rowno).getCell(colno);
String CellData = null ;
switch(cell.getCellType()){
case STRING :
CellData = cell.getStringCellValue();
break ;
case NUMERIC :
CellData = Double.toString(cell.getNumericCellValue());
if(CellData.contains(".o")){
CellData = CellData.substring(0,CellData.length()-2);
}
break ;
case BLANK :
CellData = ""; break ;
}
return CellData;
}catch(Exception e){return ""; }
}
//*************************************************************
public static int getLastRow(){
return sh.getLastRowNum();
}
You can not read & write same file in parallel(Read-write lock). But, we can do parallel operations on temporary data(i.e. Input/output stream). Write the data to file only after closing the input stream. Below steps should be followed.
Open the file to Input stream
Open the same file to an Output Stream
Read and do the processing
Write contents to output stream.
Close the read/input stream, close file
Close output stream, close file.
Apache POI - read/write same excel example
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XLSXReaderWriter {
public static void main(String[] args) {
try {
File excel = new File("D://raju.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
// Iterating over Excel file in Java
while (itr.hasNext()) {
Row row = itr.next();
// Iterating over each column of Excel file
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
}
}
System.out.println("");
}
// writing data into XLSX file
Map<String, Object[]> newData = new HashMap<String, Object[]>();
newData.put("1", new Object[] { 1d, "Raju", "75K", "dev",
"SGD" });
newData.put("2", new Object[] { 2d, "Ramesh", "58K", "test",
"USD" });
newData.put("3", new Object[] { 3d, "Ravi", "90K", "PMO",
"INR" });
Set<String> newRows = newData.keySet();
int rownum = sheet.getLastRowNum();
for (String key : newRows) {
Row row = sheet.createRow(rownum++);
Object[] objArr = newData.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof String) {
cell.setCellValue((String) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((Boolean) obj);
} else if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
}
}
}
// open an OutputStream to save written data into Excel file
FileOutputStream os = new FileOutputStream(excel);
book.write(os);
System.out.println("Writing on Excel file Finished ...");
// Close workbook, OutputStream and Excel file to prevent leak
os.close();
book.close();
fis.close();
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
Please use Apache POI libs and try this.
try
{
FileInputStream x = new FileInputStream(new File("/Users/rajesh/Documents/rajesh.xls"));
//Create Workbook instance holding reference to .xlsx file
Workbook workbook = new HSSFWorkbook(x);
//Get first/desired sheet from the workbook
Sheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
for (Iterator<Row> iterator = sheet.iterator(); iterator.hasNext();) {
Row row = (Row) iterator.next();
for (Iterator<Cell> iterator2 = row.iterator(); iterator2
.hasNext();) {
Cell cell = (Cell) iterator2.next();
System.out.println(cell.getStringCellValue());
}
}
x.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
When using the apache poi 4.1.2. The celltype changes a bit. Below is an example
try {
File excel = new File("/home/name/Downloads/bb.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
// Iterating over Excel file in Java
while (itr.hasNext()) {
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
}
}
System.out.println("");}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
If you go for third party library option, try using Aspose.Cells API that enables Java Applications to create (read/write) and manage Excel spreadsheets efficiently without requiring Microsoft Excel.
e.g
Sample code:
1.
//Load sample workbook
Workbook wb = new Workbook(dirPath + "sample.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access cells iterator
Iterator itrat = ws.getCells().iterator();
//Print cells name in iterator
while(itrat.hasNext())
{
Cell cell = (Cell)itrat.next();
System.out.println(cell.getName() + ": " + cell.getStringValue().trim());
}
Workbook book = new Workbook("sample.xlsx");
Worksheet sheet = book.getWorksheets().get(0);
Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
Iterator rangeIterator = range.iterator();
while(rangeIterator.hasNext())
{
Cell cell = (Cell)rangeIterator.next();
//your code goes here.
}
Hope, this helps a bit.
PS. I am working as Support developer/ Evangelist at Aspose.
If you need to do anything more with office documents in Java, go for POI as mentioned.
For simple reading/writing an excel document like you requested, you can use the CSV format (also as mentioned):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CsvWriter {
public static void main(String args[]) throws IOException {
String fileName = "test.xls";
PrintWriter out = new PrintWriter(new FileWriter(fileName));
out.println("a,b,c,d");
out.println("e,f,g,h");
out.println("i,j,k,l");
out.close();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = in.readLine()) != null) {
Scanner scanner = new Scanner(line);
String sep = "";
while (scanner.hasNext()) {
System.out.println(sep + scanner.next());
sep = ",";
}
}
in.close();
}
}
This will write a JTable to a tab separated file that can be easily imported into Excel. This works.
If you save an Excel worksheet as an XML document you could also build the XML file for EXCEL with code. I have done this with word so you do not have to use third-party packages.
This could code have the JTable taken out and then just write a tab separated to any text file and then import into Excel. I hope this helps.
Code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.TableModel;
public class excel {
String columnNames[] = { "Column 1", "Column 2", "Column 3" };
// Create some data
String dataValues[][] =
{
{ "12", "234", "67" },
{ "-123", "43", "853" },
{ "93", "89.2", "109" },
{ "279", "9033", "3092" }
};
JTable table;
excel() {
table = new JTable( dataValues, columnNames );
}
public void toExcel(JTable table, File file){
try{
TableModel model = table.getModel();
FileWriter excel = new FileWriter(file);
for(int i = 0; i < model.getColumnCount(); i++){
excel.write(model.getColumnName(i) + "\t");
}
excel.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
excel.write(model.getValueAt(i,j).toString()+"\t");
}
excel.write("\n");
}
excel.close();
}catch(IOException e){ System.out.println(e); }
}
public static void main(String[] o) {
excel cv = new excel();
cv.toExcel(cv.table,new File("C:\\Users\\itpr13266\\Desktop\\cs.tbv"));
}
}
I am reading data from an arraylist and writing this to an excel sheet. The problem is my excel is getting overwritten each time. Here is my code. I can't figure out what is wrong here :( Can someone please help?
public static void main( String[] args ) throws Exception
{
List<String> fileData = new ArrayList<String>();
for(File file:files) {
fileData.add(readFileContents(file.getAbsolutePath()));
}
for(String fileContent:fileData) {
//do some stuff that in turn calls the writeDataToExcel method
}
}
private static void writeDataToExcel(String test,Map<String,String> dataMap,Object object) throws IOException {
File file = new File("input/data.xls");
Map<String,Object[]> data = new LinkedHashMap<String,Object[]>();
XSSFWorkbook workbook = null;
int count = 0;
XSSFSheet sheet = null;
if(file.exists()) {
workbook = new XSSFWorkbook(new FileInputStream(file));
sheet = workbook.getSheet("Data Sheet");
}
else {
workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Data Sheet");
//count = sheet.getLastRowNum();
}
data.put("1", new Object[]{"Id","Name","Field","Description","Value"});
for(Map.Entry<String, String> dataMp:dataMap.entrySet()) {
data.put(Integer.toString(count+2), new Object[]{id,object.getClass().getSimpleName(),dataMp.getKey(),dataMp.getValue(),"null"});
count++;
}
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof String)
cell.setCellValue((String)obj);
}
}
FileOutputStream fis = new FileOutputStream("input/data.xls");
workbook.write(fis);
if(fis!=null)
fis.close();
}
I think problem is at line
int rownum = 0;
this will set rowNUm to zero each time and sheet will be written from zero row
You need to persist this rowNum value if you want to append data in the sheet
i'm using Apache POI(XSSF API) for reading xlsx file.when i tried to read file.i got the following error:
org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
Code:
public class ReadXLSX
{
private String filepath;
private XSSFWorkbook workbook;
private static Logger logger=null;
private InputStream resourceAsStream;
public ReadXLSX(String FilePath)
{
logger=LoggerFactory.getLogger("ReadXLSX");
this.filepath=FilePath;
resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);
}
public ReadXLSX(InputStream fileStream)
{
logger=LoggerFactory.getLogger("ReadXLSX");
this.resourceAsStream=fileStream;
}
private void loadFile() throws FileNotFoundException, NullObjectFoundException
{
if(resourceAsStream==null)
throw new FileNotFoundException("Unable to locate give file..");
else
{
try
{
workbook = new XSSFWorkbook(resourceAsStream);
}
catch(IOException ex)
{
}
}
}// end loadxlsFile
public String[] getSheetsName()
{
int totalsheet=0;int i=0;
String[] sheetName=null;
try {
loadFile();
totalsheet=workbook.getNumberOfSheets();
sheetName=new String[totalsheet];
while(i<totalsheet)
{
sheetName[i]=workbook.getSheetName(i);
i++;
}
} catch (FileNotFoundException ex) {
logger.error(ex);
} catch (NullObjectFoundException ex) {
logger.error(ex);
}
return sheetName;
}
public int[] getSheetsIndex()
{
int totalsheet=0;int i=0;
int[] sheetIndex=null;
String[] sheetname=getSheetsName();
try {
loadFile();
totalsheet=workbook.getNumberOfSheets();
sheetIndex=new int[totalsheet];
while(i<totalsheet)
{
sheetIndex[i]=workbook.getSheetIndex(sheetname[i]);
i++;
}
} catch (FileNotFoundException ex) {
logger.error(ex);
} catch (NullObjectFoundException ex) {
logger.error(ex);
}
return sheetIndex;
}
private boolean validateIndex(int index)
{
if(index < getSheetsIndex().length && index >=0)
return true;
else
return false;
}
public int getNumberOfSheet()
{
int totalsheet=0;
try {
loadFile();
totalsheet=workbook.getNumberOfSheets();
} catch (FileNotFoundException ex) {
logger.error(ex.getMessage());
} catch (NullObjectFoundException ex) {
logger.error(ex.getMessage());
}
return totalsheet;
}
public int getNumberOfColumns(int SheetIndex)
{
int NO_OF_Column=0;XSSFCell cell = null;
XSSFSheet sheet=null;
try {
loadFile(); //load give Excel
if(validateIndex(SheetIndex))
{
sheet = workbook.getSheetAt(SheetIndex);
Iterator rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator cellIter = firstRow.cellIterator();
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
}
else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
logger.error(ex.getMessage());
}
return NO_OF_Column;
}
public int getNumberOfRows(int SheetIndex)
{
int NO_OF_ROW=0; XSSFSheet sheet=null;
try {
loadFile(); //load give Excel
if(validateIndex(SheetIndex))
{
sheet = workbook.getSheetAt(SheetIndex);
NO_OF_ROW = sheet.getLastRowNum();
}
else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
logger.error(ex);}
return NO_OF_ROW;
}
public String[] getSheetHeader(int SheetIndex)
{
int noOfColumns = 0;XSSFCell cell = null; int i =0;
String columns[] = null; XSSFSheet sheet=null;
try {
loadFile(); //load give Excel
if(validateIndex(SheetIndex))
{
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
columns = new String[noOfColumns];
Iterator rowIter = sheet.rowIterator();
XSSFRow Row = (XSSFRow) rowIter.next();
Iterator cellIter = Row.cellIterator();
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
columns[i] = cell.getStringCellValue();
i++;
}
}
else
throw new InvalidSheetIndexException("Invalid sheet index.");
}
catch (Exception ex) {
logger.error(ex);}
return columns;
}//end of method
public String[][] getSheetData(int SheetIndex)
{
int noOfColumns = 0;XSSFRow row = null;
XSSFCell cell = null;
int i=0;int noOfRows=0;
int j=0;
String[][] data=null; XSSFSheet sheet=null;
try {
loadFile(); //load give Excel
if(validateIndex(SheetIndex))
{
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
noOfRows =getNumberOfRows(SheetIndex)+1;
data = new String[noOfRows][noOfColumns];
Iterator rowIter = sheet.rowIterator();
while(rowIter.hasNext())
{
row = (XSSFRow) rowIter.next();
Iterator cellIter = row.cellIterator();
j=0;
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
if(cell.getCellType() == cell.CELL_TYPE_STRING)
{
data[i][j] = cell.getStringCellValue();
}
else if(cell.getCellType() == cell.CELL_TYPE_NUMERIC)
{
if (HSSFDateUtil.isCellDateFormatted(cell))
{
String formatCellValue = new DataFormatter().formatCellValue(cell);
data[i][j] =formatCellValue;
}
else
{
data[i][j] = Double.toString(cell.getNumericCellValue());
}
}
else if(cell.getCellType() == cell.CELL_TYPE_BOOLEAN)
{
data[i][j] = Boolean.toString(cell.getBooleanCellValue());
}
else if(cell.getCellType() == cell.CELL_TYPE_FORMULA)
{
data[i][j] = cell.getCellFormula().toString();
}
j++;
}
i++;
} // outer while
}
else throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
logger.error(ex);}
return data;
}
public String[][] getSheetData(int SheetIndex,int noOfRows)
{
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i=0;
int j=0;
String[][] data=null;
XSSFSheet sheet=null;
try {
loadFile(); //load give Excel
if(validateIndex(SheetIndex))
{
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
data = new String[noOfRows][noOfColumns];
Iterator rowIter = sheet.rowIterator();
while(i<noOfRows)
{
row = (XSSFRow) rowIter.next();
Iterator cellIter = row.cellIterator();
j=0;
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
if(cell.getCellType() == cell.CELL_TYPE_STRING)
{
data[i][j] = cell.getStringCellValue();
}
else if(cell.getCellType() == cell.CELL_TYPE_NUMERIC)
{
if (HSSFDateUtil.isCellDateFormatted(cell))
{
String formatCellValue = new DataFormatter().formatCellValue(cell);
data[i][j] =formatCellValue;
}
else
{
data[i][j] = Double.toString(cell.getNumericCellValue());
}
}
j++;
}
i++;
} // outer while
}else throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
logger.error(ex);
}
return data;
}
please help me to sort out this problem.
Thanks
The error is telling you that POI couldn't find a core part of the OOXML file, in this case the content types part. Your file isn't a valid OOXML file, let alone a valid .xlsx file. It is a valid zip file though, otherwise you'd have got an earlier error
Can Excel really load this file? I'd expect it wouldn't be able to, as the exception is most commonly triggered by giving POI a regular .zip file! I suspect your file isn't valid, hence the exception
.
Update: In Apache POI 3.15 (from beta 1 onwards), there's a more helpful set of Exception messages for the more common causes of this problem. You'll now get more descriptive exceptions in this case, eg ODFNotOfficeXmlFileException and OLE2NotOfficeXmlFileException. This raw form should only ever show up if POI really has no clue what you've given it but knows it's broken or invalid.
Pretty sure that this exception is thrown when the Excel file is either password protected or the file itself is corrupted. If you just want to read a .xlsx file, try my code below. It's a lot more shorter and easier to read.
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
//.....
static final String excelLoc = "C:/Documents and Settings/Users/Desktop/testing.xlsx";
public static void ReadExcel() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(excelLoc));
Workbook wb = WorkbookFactory.create(inputStream);
int numberOfSheet = wb.getNumberOfSheets();
for (int i = 0; i < numberOfSheet; i++) {
Sheet sheet = wb.getSheetAt(i);
//.... Customize your code here
// To get sheet name, try -> sheet.getSheetName()
}
} catch {}
}
You get this exact error should you pass an old school .xls file into this API. Save the .xls as a .xlsx and then it will work.
I was using XSSFWorkbook to read .xls, which resulted in InvalidFormatException. I have to use a more generic Workbook and Sheet to make it work.
This post helped me solved my problem.
You might also see this error if you attempt to parse the same file twice from the same source.
I was parsing the file once to validate and again (from the same InputStream) to process - this produced the above error.
To get round this I parsed the source file into 2 different InputStreams, one to validate and one to process.
Cleaned up the code (commented out the logger mostly) to make it run in my Eclipse environment.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
public class ReadXLSX {
private String filepath;
private XSSFWorkbook workbook;
// private static Logger logger=null;
private InputStream resourceAsStream;
public ReadXLSX(String filePath) {
// logger=LoggerFactory.getLogger("ReadXLSX");
this.filepath = filePath;
resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);
}
public ReadXLSX(InputStream fileStream) {
// logger=LoggerFactory.getLogger("ReadXLSX");
this.resourceAsStream = fileStream;
}
private void loadFile() throws FileNotFoundException,
NullObjectFoundException {
if (resourceAsStream == null)
throw new FileNotFoundException("Unable to locate give file..");
else {
try {
workbook = new XSSFWorkbook(resourceAsStream);
} catch (IOException ex) {
}
}
}// end loadxlsFile
public String[] getSheetsName() {
int totalsheet = 0;
int i = 0;
String[] sheetName = null;
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
sheetName = new String[totalsheet];
while (i < totalsheet) {
sheetName[i] = workbook.getSheetName(i);
i++;
}
} catch (FileNotFoundException ex) {
// logger.error(ex);
} catch (NullObjectFoundException ex) {
// logger.error(ex);
}
return sheetName;
}
public int[] getSheetsIndex() {
int totalsheet = 0;
int i = 0;
int[] sheetIndex = null;
String[] sheetname = getSheetsName();
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
sheetIndex = new int[totalsheet];
while (i < totalsheet) {
sheetIndex[i] = workbook.getSheetIndex(sheetname[i]);
i++;
}
} catch (FileNotFoundException ex) {
// logger.error(ex);
} catch (NullObjectFoundException ex) {
// logger.error(ex);
}
return sheetIndex;
}
private boolean validateIndex(int index) {
if (index < getSheetsIndex().length && index >= 0)
return true;
else
return false;
}
public int getNumberOfSheet() {
int totalsheet = 0;
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
} catch (FileNotFoundException ex) {
// logger.error(ex.getMessage());
} catch (NullObjectFoundException ex) {
// logger.error(ex.getMessage());
}
return totalsheet;
}
public int getNumberOfColumns(int SheetIndex) {
int NO_OF_Column = 0;
#SuppressWarnings("unused")
XSSFCell cell = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
Iterator<Row> rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = firstRow.cellIterator();
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex.getMessage());
}
return NO_OF_Column;
}
public int getNumberOfRows(int SheetIndex) {
int NO_OF_ROW = 0;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
NO_OF_ROW = sheet.getLastRowNum();
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return NO_OF_ROW;
}
public String[] getSheetHeader(int SheetIndex) {
int noOfColumns = 0;
XSSFCell cell = null;
int i = 0;
String columns[] = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
columns = new String[noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
XSSFRow Row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = Row.cellIterator();
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
columns[i] = cell.getStringCellValue();
i++;
}
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
}
catch (Exception ex) {
// logger.error(ex);
}
return columns;
}// end of method
public String[][] getSheetData(int SheetIndex) {
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i = 0;
int noOfRows = 0;
int j = 0;
String[][] data = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
noOfRows = getNumberOfRows(SheetIndex) + 1;
data = new String[noOfRows][noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
while (rowIter.hasNext()) {
row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
j = 0;
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
data[i][j] = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
String formatCellValue = new DataFormatter()
.formatCellValue(cell);
data[i][j] = formatCellValue;
} else {
data[i][j] = Double.toString(cell
.getNumericCellValue());
}
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
data[i][j] = Boolean.toString(cell
.getBooleanCellValue());
}
else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
data[i][j] = cell.getCellFormula().toString();
}
j++;
}
i++;
} // outer while
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return data;
}
public String[][] getSheetData(int SheetIndex, int noOfRows) {
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i = 0;
int j = 0;
String[][] data = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
data = new String[noOfRows][noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
while (i < noOfRows) {
row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
j = 0;
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
data[i][j] = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
String formatCellValue = new DataFormatter()
.formatCellValue(cell);
data[i][j] = formatCellValue;
} else {
data[i][j] = Double.toString(cell
.getNumericCellValue());
}
}
j++;
}
i++;
} // outer while
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return data;
}
}
Created this little testcode:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReadXLSXTest {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
ReadXLSX test = new ReadXLSX(new FileInputStream(new File("./sample.xlsx")));
System.out.println(test.getSheetsName());
System.out.println(test.getNumberOfSheet());
}
}
All this ran like a charm, so my guess is you have an XLSX file that is 'corrupt' in one way or another. Try testing with other data.
Cheers,
Wim
I get the same exception for .xls file, but after I open the file and save it as xlsx file , the below code works:
try(InputStream is =file.getInputStream()){
XSSFWorkbook workbook = new XSSFWorkbook(is);
...
}
If the excel file is password protected, then this error comes up.
Try saving the file as Excel Workbook ONLY. NOT any other format. It worked for me. I was getting the same error.
I was able to solve this issue by either
Open and resave the file using MS-EXCEL
Open the file using the Woorbookfactory:
Workbook workbook = WorkbookFactory.create(byteFile);
I want to read and write an Excel file from Java with 3 columns and N rows, printing one string in each cell. Can anyone give me simple code snippet for this? Do I need to use any external lib or does Java have built-in support for it?
I want to do the following:
for(i=0; i <rows; i++)
//read [i,col1] ,[i,col2], [i,col3]
for(i=0; i<rows; i++)
//write [i,col1], [i,col2], [i,col3]
Try the Apache POI HSSF. Here's an example on how to read an excel file:
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell((short)c);
if(cell != null) {
// Your code here
}
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}
On the documentation page you also have examples of how to write to excel files.
Apache POI can do this for you. Specifically the HSSF module. The quick guide is most useful. Here's how to do what you want - specifically create a sheet and write it out.
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
First add all these jar files in your project class path:
poi-scratchpad-3.7-20101029
poi-3.2-FINAL-20081019
poi-3.7-20101029
poi-examples-3.7-20101029
poi-ooxml-3.7-20101029
poi-ooxml-schemas-3.7-20101029
xmlbeans-2.3.0
dom4j-1.6.1
Code for writing in a excel file:
public static void main(String[] args) {
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Employee Data");
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[]{"ID", "NAME", "LASTNAME"});
data.put("2", new Object[]{1, "Amit", "Shukla"});
data.put("3", new Object[]{2, "Lokesh", "Gupta"});
data.put("4", new Object[]{3, "John", "Adwards"});
data.put("5", new Object[]{4, "Brian", "Schultz"});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
//create a row of excelsheet
Row row = sheet.createRow(rownum++);
//get object array of prerticuler key
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if (obj instanceof String)
{
cell.setCellValue((String) obj);
}
else if (obj instanceof Integer)
{
cell.setCellValue((Integer) obj);
}
}
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
workbook.write(out);
out.close();
System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
Code for reading from excel file
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You can also consider JExcelApi. I find it better designed than POI. There's a tutorial here.
There is a new easy and very cool tool (10x to Kfir): xcelite
Write:
public class User {
#Column (name="Firstname")
private String firstName;
#Column (name="Lastname")
private String lastName;
#Column
private long id;
#Column
private Date birthDate;
}
Xcelite xcelite = new Xcelite();
XceliteSheet sheet = xcelite.createSheet("users");
SheetWriter<User> writer = sheet.getBeanWriter(User.class);
List<User> users = new ArrayList<User>();
// ...fill up users
writer.write(users);
xcelite.write(new File("users_doc.xlsx"));
Read:
Xcelite xcelite = new Xcelite(new File("users_doc.xlsx"));
XceliteSheet sheet = xcelite.getSheet("users");
SheetReader<User> reader = sheet.getBeanReader(User.class);
Collection<User> users = reader.read();
For reading a xlsx file we can use Apache POI libs
Try this:
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
.csv or POI will certainly do it, but you should be aware of Andy Khan's JExcel. I think it's by far the best Java library for working with Excel there is.
A simple CSV file should suffice
String path="C:\\Book2.xlsx";
try {
File f = new File( path );
Workbook wb = WorkbookFactory.create(f);
Sheet mySheet = wb.getSheetAt(0);
Iterator<Row> rowIter = mySheet.rowIterator();
for ( Iterator<Row> rowIterator = mySheet.rowIterator() ;rowIterator.hasNext(); )
{
for ( Iterator<Cell> cellIterator = ((Row)rowIterator.next()).cellIterator() ; cellIterator.hasNext() ; )
{
System.out.println ( ( (Cell)cellIterator.next() ).toString() );
}
System.out.println( " **************************************************************** ");
}
} catch ( Exception e )
{
System.out.println( "exception" );
e.printStackTrace();
}
and make sure to have added the jars poi and poi-ooxml (org.apache.poi) to your project
For reading data from .xlsx workbooks we need to use XSSFworkbook classes.
XSSFWorkbook xlsxBook = new XSSFWorkbook(fis);
XSSFSheet sheet = xlsxBook.getSheetAt(0); etc.
We need to use Apache-poi 3.9 # http://poi.apache.org/
For detailed info with example visit
: http://java-recent.blogspot.in
Sure , you will find the code below useful and easy to read and write. This is a util class which you can use in your main method and then you are good to use all methods below.
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
public void setExcelFile(File Path, String SheetName) throws Exception
try {
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {
try {
Row = ExcelWSheet.createRow(RowNum - 1);
Cell = Row.createCell(ColNum - 1);
Cell.setCellValue(Result);
FileOutputStream fileOut = new FileOutputStream(Path);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
using spring apache poi repo
if (fileName.endsWith(".xls")) {
File myFile = new File("file location" + fileName);
FileInputStream fis = new FileInputStream(myFile);
org.apache.poi.ss.usermodel.Workbook workbook = null;
try {
workbook = WorkbookFactory.create(fis);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue());
break;
}
System.out.print(" - ");
}
System.out.println();
}
}
I edited the most voted one a little cuz it didn't count blanks columns or rows well not totally, so here is my code i tested it and now can get any cell in any part of an excel file. also now u can have blanks columns between filled column and it will read them
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
int cblacks=0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i <= 10 || i <= rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp >= cols) cols = tmp;else{rows++;cblacks++;}
}
cols++;
}
cols=cols+cblacks;
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell(c);
if(cell != null) {
System.out.print(cell+"\n");//Your Code here
}
}
}
}} catch(Exception ioe) {
ioe.printStackTrace();}
If column number are varing you can use this
package com.org.tests;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelSimpleTest
{
String path;
public FileInputStream fis = null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row =null;
private XSSFCell cell = null;
public ExcelSimpleTest() throws IOException
{
path = System.getProperty("user.dir")+"\\resources\\Book1.xlsx";
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
}
public void ExelWorks()
{
int index = workbook.getSheetIndex("Sheet1");
sheet = workbook.getSheetAt(index);
int rownumber=sheet.getLastRowNum()+1;
for (int i=1; i<rownumber; i++ )
{
row = sheet.getRow(i);
int colnumber = row.getLastCellNum();
for (int j=0; j<colnumber; j++ )
{
cell = row.getCell(j);
System.out.println(cell.getStringCellValue());
}
}
}
public static void main(String[] args) throws IOException
{
ExcelSimpleTest excelwork = new ExcelSimpleTest();
excelwork.ExelWorks();
}
}
The corresponding mavendependency can be found here
Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.
Import data
try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
rowStream
// skip the header row that contains the column names
.skip(1)
.forEach(row -> {
System.out.println(
"row n°" + row.rowIndex()
+ " column 'User login' value : " + row.cell("User login").asString()
+ " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
);
});
}
Export data
Windmill
.export(Arrays.asList(bean1, bean2, bean3))
.withHeaderMapping(
new ExportHeaderMapping<Bean>()
.add("Name", Bean::getName)
.add("User login", bean -> bean.getUser().getLogin())
)
.asExcel()
.writeTo(new FileOutputStream("Export.xlsx"));
You need Apache POI library and this code below should help you
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
//*************************************************************
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//*************************************************************
public class AdvUse {
private static Workbook wb ;
private static Sheet sh ;
private static FileInputStream fis ;
private static FileOutputStream fos ;
private static Row row ;
private static Cell cell ;
private static String ExcelPath ;
//*************************************************************
public static void setEcxelFile(String ExcelPath, String SheetName) throws Exception {
try {
File f= new File(ExcelPath);
if(!f.exists()){
f.createNewFile();
System.out.println("File not Found so created");
}
fis = new FileInputStream("./testData.xlsx");
wb = WorkbookFactory.create(fis);
sh = wb.getSheet("SheetName");
if(sh == null){
sh = wb.getSheet(SheetName);
}
}catch(Exception e)
{System.out.println(e.getMessage());
}
}
//*************************************************************
public static void setCellData(String text , int rowno , int colno){
try{
row = sh.getRow(rowno);
if(row == null){
row = sh.createRow(rowno);
}
cell = row.getCell(colno);
if(cell!=null){
cell.setCellValue(text);
}
else{
cell = row.createCell(colno);
cell.setCellValue(text);
}
fos = new FileOutputStream(ExcelPath);
wb.write(fos);
fos.flush();
fos.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
//*************************************************************
public static String getCellData(int rowno , int colno){
try{
cell = sh.getRow(rowno).getCell(colno);
String CellData = null ;
switch(cell.getCellType()){
case STRING :
CellData = cell.getStringCellValue();
break ;
case NUMERIC :
CellData = Double.toString(cell.getNumericCellValue());
if(CellData.contains(".o")){
CellData = CellData.substring(0,CellData.length()-2);
}
break ;
case BLANK :
CellData = ""; break ;
}
return CellData;
}catch(Exception e){return ""; }
}
//*************************************************************
public static int getLastRow(){
return sh.getLastRowNum();
}
You can not read & write same file in parallel(Read-write lock). But, we can do parallel operations on temporary data(i.e. Input/output stream). Write the data to file only after closing the input stream. Below steps should be followed.
Open the file to Input stream
Open the same file to an Output Stream
Read and do the processing
Write contents to output stream.
Close the read/input stream, close file
Close output stream, close file.
Apache POI - read/write same excel example
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XLSXReaderWriter {
public static void main(String[] args) {
try {
File excel = new File("D://raju.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
// Iterating over Excel file in Java
while (itr.hasNext()) {
Row row = itr.next();
// Iterating over each column of Excel file
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
}
}
System.out.println("");
}
// writing data into XLSX file
Map<String, Object[]> newData = new HashMap<String, Object[]>();
newData.put("1", new Object[] { 1d, "Raju", "75K", "dev",
"SGD" });
newData.put("2", new Object[] { 2d, "Ramesh", "58K", "test",
"USD" });
newData.put("3", new Object[] { 3d, "Ravi", "90K", "PMO",
"INR" });
Set<String> newRows = newData.keySet();
int rownum = sheet.getLastRowNum();
for (String key : newRows) {
Row row = sheet.createRow(rownum++);
Object[] objArr = newData.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof String) {
cell.setCellValue((String) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((Boolean) obj);
} else if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
}
}
}
// open an OutputStream to save written data into Excel file
FileOutputStream os = new FileOutputStream(excel);
book.write(os);
System.out.println("Writing on Excel file Finished ...");
// Close workbook, OutputStream and Excel file to prevent leak
os.close();
book.close();
fis.close();
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
Please use Apache POI libs and try this.
try
{
FileInputStream x = new FileInputStream(new File("/Users/rajesh/Documents/rajesh.xls"));
//Create Workbook instance holding reference to .xlsx file
Workbook workbook = new HSSFWorkbook(x);
//Get first/desired sheet from the workbook
Sheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
for (Iterator<Row> iterator = sheet.iterator(); iterator.hasNext();) {
Row row = (Row) iterator.next();
for (Iterator<Cell> iterator2 = row.iterator(); iterator2
.hasNext();) {
Cell cell = (Cell) iterator2.next();
System.out.println(cell.getStringCellValue());
}
}
x.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
When using the apache poi 4.1.2. The celltype changes a bit. Below is an example
try {
File excel = new File("/home/name/Downloads/bb.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
// Iterating over Excel file in Java
while (itr.hasNext()) {
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
}
}
System.out.println("");}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
If you go for third party library option, try using Aspose.Cells API that enables Java Applications to create (read/write) and manage Excel spreadsheets efficiently without requiring Microsoft Excel.
e.g
Sample code:
1.
//Load sample workbook
Workbook wb = new Workbook(dirPath + "sample.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access cells iterator
Iterator itrat = ws.getCells().iterator();
//Print cells name in iterator
while(itrat.hasNext())
{
Cell cell = (Cell)itrat.next();
System.out.println(cell.getName() + ": " + cell.getStringValue().trim());
}
Workbook book = new Workbook("sample.xlsx");
Worksheet sheet = book.getWorksheets().get(0);
Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
Iterator rangeIterator = range.iterator();
while(rangeIterator.hasNext())
{
Cell cell = (Cell)rangeIterator.next();
//your code goes here.
}
Hope, this helps a bit.
PS. I am working as Support developer/ Evangelist at Aspose.
If you need to do anything more with office documents in Java, go for POI as mentioned.
For simple reading/writing an excel document like you requested, you can use the CSV format (also as mentioned):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CsvWriter {
public static void main(String args[]) throws IOException {
String fileName = "test.xls";
PrintWriter out = new PrintWriter(new FileWriter(fileName));
out.println("a,b,c,d");
out.println("e,f,g,h");
out.println("i,j,k,l");
out.close();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = in.readLine()) != null) {
Scanner scanner = new Scanner(line);
String sep = "";
while (scanner.hasNext()) {
System.out.println(sep + scanner.next());
sep = ",";
}
}
in.close();
}
}
This will write a JTable to a tab separated file that can be easily imported into Excel. This works.
If you save an Excel worksheet as an XML document you could also build the XML file for EXCEL with code. I have done this with word so you do not have to use third-party packages.
This could code have the JTable taken out and then just write a tab separated to any text file and then import into Excel. I hope this helps.
Code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.TableModel;
public class excel {
String columnNames[] = { "Column 1", "Column 2", "Column 3" };
// Create some data
String dataValues[][] =
{
{ "12", "234", "67" },
{ "-123", "43", "853" },
{ "93", "89.2", "109" },
{ "279", "9033", "3092" }
};
JTable table;
excel() {
table = new JTable( dataValues, columnNames );
}
public void toExcel(JTable table, File file){
try{
TableModel model = table.getModel();
FileWriter excel = new FileWriter(file);
for(int i = 0; i < model.getColumnCount(); i++){
excel.write(model.getColumnName(i) + "\t");
}
excel.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
excel.write(model.getValueAt(i,j).toString()+"\t");
}
excel.write("\n");
}
excel.close();
}catch(IOException e){ System.out.println(e); }
}
public static void main(String[] o) {
excel cv = new excel();
cv.toExcel(cv.table,new File("C:\\Users\\itpr13266\\Desktop\\cs.tbv"));
}
}