Sie sind auf Seite 1von 7

How to Handle Excel files in Java

There are many solutions to read or write Excel spreadsheets from Java. This HowTo is only about OpenSource (and
free) solutions.

JDBC-ODBC Excel driver


This solution lets you access your Excel worksheet with SQL SELECT statement. The required ODBC driver is included in
a regular Windows installation and the JDBC-ODBC bridge is used to access the Excel DSN.

See this HowTo for an example.

JExcel
Java Excel API is a java API enabling developers to read, write, and modify Excel spreadsheets dynamically. Any
operating system which can run a Java virtual machine can both process and deliver Excel spreadsheets. One nice thing
about JExcelApi is that it has no dependencies on any third party libraries.

Example : output an Excel file from a Servlet

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class Sample extends HttpServlet {


public void doGet
(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
OutputStream out = null;
try {
response.setContentType("application/vnd.ms-excel");
response.setHeader
("Content-Disposition", "attachment; filename=sampleName.xls");
WritableWorkbook w =
Workbook.createWorkbook(response.getOutputStream());
WritableSheet s = w.createSheet("Demo", 0);
s.addCell(new Label(0, 0, "Hello World"));
w.write();
w.close();
}
catch (Exception e){
throw new ServletException("Exception in Excel Sample Servlet", e);
}
finally{
if (out != null)
out.close();
}
}
}

See http://jexcelapi.sourceforge.net/

POI
The POI project consists of APIs for manipulating various file formats based upon Microsoft's OLE 2 Compound
Document format using pure Java. POI is your Java Excel solution as well as your Java Word solution.

HSSF is the POI Project's pure Java implementation of the Excel '97(-2002) file format and it provides a way to read
spreadsheets create, modify, read and write XLS spreadsheets. Latest POI version seems to support the .XLSX format.

Since it's Jakarta project, POI has a dependencies with other JARs (commons,log4j,etc...).

Example : create an Excel file

HSSFWorkbook wb = new HSSFWorkbook();


HSSFSheet sheet = wb.createSheet("new sheet");

HSSFRow row = sheet.createRow((short)0);


row.createCell((short)0).setCellValue("HelloWorld");

FileOutputStream fileOut = new FileOutputStream("workbook.xls");


wb.write(fileOut);
fileOut.close();

The name was originally an acronym for "Poor Obfuscation Implementation" (ref: Wikipedia).

See http://jakarta.apache.org/poi/

JXLS
jXLS is a project that allows creation of extremely complex Excel reports just in several lines of code. It is based on
Jakarta POI.

With jXLS, all you need is to create XLS template file with all required formatting, formulas etc using specific notation to
indicate placement of data and then write a couple lines of code to invoke jXLS engine passing XLS template and the
exported data as parameters.

Example :
The XLS Template

Employees
Name Age Payment Bonus
${employee.name} ${employee.age} ${employee.payment} ${employee.bonus}
$[SUM(@employee.payment@)]

with the code

Collection staff = new HashSet();


staff.add(new Employee("Derek", 35, 3000, 0.30));
staff.add(new Employee("Elsa", 28, 1500, 0.15));
Map beans = new HashMap();
beans.put("employee", staff);
XLSTransformer transformer = new XLSTransformer();
transformer.transformXLS(templateFileName, beans, destFileName);
gives the result
Employees
Name Age Payment Bonus
Derek 35 3000 30,00%
Else 28 1500 15,00%
4500
Reading values from an XLS with jXLS is very simple. Suppose we have a worksheet with policy numbers in the first
column. We read and process them one by one.
import java.io.File;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

public void doit() throws Exception {


Workbook workbook = Workbook.getWorkbook(new File("policies.xls"));
Sheet sheet = workbook.getSheet(0);
Cell policies[] = sheet.getColumn(0);
for (Cell policy : policies) {
String nopolicy = policy.getContents();
// do something : process(nopolicy);
}
}

See http://jxls.sourceforge.net/

xlSQL
xlSQL is a JDBC Driver for Excel and CSV data sources. Documents can be read and written with SQL as if they were
tables in a database.

You can export XLS to XML or SQL INSERT statements. xlSQL includes its own "zero-admin" mySQL database. The
documentation is minimal at this time.

See http://xlsql.sourceforge.net/

JCOM
JCOM is a Java to COM bridge library. With JCOM you can call a COM object from Java as if it were a Java object
without having to deal with the internals of JNI. The documentation is minimal (in Japanese!).

Example :

import jp.ne.so_net.ga2.no_ji.jcom.excel8.*;
import jp.ne.so_net.ga2.no_ji.jcom.*;
import java.io.File;
import java.util.Date;

class TestExcel {
public static void main(String[] args) throws Exception {
ReleaseManager rm = new ReleaseManager();
try {
System.out.println("EXCEL startup...");
// if already started, open new window
ExcelApplication excel = new ExcelApplication(rm);
excel.Visible(true);
// display any information
System.out.println("Version="+excel.Version());
System.out.println("UserName="+excel.UserName());
System.out.println("Caption="+excel.Caption());
System.out.println("Value="+excel.Value());

ExcelWorkbooks xlBooks = excel.Workbooks();


ExcelWorkbook xlBook = xlBooks.Add(); // create new book

// enumurate all files


System.out.println
("set infomation of files in current directory to cell ...");
ExcelWorksheets xlSheets = xlBook.Worksheets();
ExcelWorksheet xlSheet = xlSheets.Item(1);
ExcelRange xlRange = xlSheet.Cells();

xlRange.Item(1,1).Value("filename" );
xlRange.Item(2,1).Value("size" );
xlRange.Item(3,1).Value("last modified time");
xlRange.Item(4,1).Value("is directory");
xlRange.Item(5,1).Value("is file");
xlRange.Item(6,1).Value("can read");
xlRange.Item(7,1).Value("can write");

File path = new File("./");


String[] filenames = path.list();
for(int i=0; i<filenames.length; i++) {
File file = new File(filenames[i]);
System.out.println(file);
xlRange.Item(1,i+2).Value( file.getName() );
xlRange.Item(2,i+2).Value( (int)file.length() );
xlRange.Item(3,i+2).Value( new Date(file.lastModified()) );
xlRange.Item(4,i+2).Value( file.isDirectory()?"Yes":"No" );
xlRange.Item(5,i+2).Value( file.isFile()?"Yes":"No" );
xlRange.Item(6,i+2).Value( file.canRead()?"Yes":"No" );
xlRange.Item(7,i+2).Value( file.canWrite()?"Yes":"No" );
}
String expression = "=Sum(B2:B"+(filenames.length+1)+")";
System.out.println
("embed equation, calculate sum of filesize: "+expression);
xlRange.Item(1,filenames.length+2).Value("sum");
xlRange.Item(2,filenames.length+2).Formula(expression);
xlRange.Columns().AutoFit(); // fit columns

// comment out, if print out.


// output default printer.
// System.out.println("print out...");
// xlSheet.PrintOut();
// comment out, if book save to file.
// if no path, save to(My Documents)
// System.out.println
// ("save to file... (My Documents)\\testExcel.xls");
// xlBook.SaveAs("testExcel.xls");

xlBook.Close(false,null,false);
excel.Quit();

System.out.println("thank you .");


}
catch(Exception e) { e.printStackTrace(); }
finally { rm.release(); }
}
}

See http://sourceforge.net/projects/jcom

See also this HowTo for an alternative package to access a COM package from Java.

OpenXLS Java Spreadsheet SDK


OpenXLS claims that it has the best compatibility with complex Excel files and able to handle any kind of Excel file out
there without corrupting it. This open source effort is the result of over 6 years of development into it.

See http://www.extentech.com/estore/product_detail.jsp?product_group_id=228

Example (extract 3 images from a workbook, create a new workbook with them) :

doit("testImages.xls","Sheet1");

...

void doit(String finpath, String sheetname){


System.out.println("Begin parsing: " + workingdir + finpath);
WorkBookHandle tbo = new WorkBookHandle(workingdir + finpath);

try{
sheet = tbo.getWorkSheet(sheetname);
// read images from sheet 1 -- .gif, .png, .jpg
ImageHandle[] extracted = sheet.getImages();
// extract and output images
for(int t=0;t<extracted.length;t++) {
System.out.println("Successfully extracted: "
+ workingdir + "testImageOut_"
+ extracted[t].getName()+"."
+extracted[t].getType());
FileOutputStream outimg = new FileOutputStream
(workingdir + extracted[t].getName()+"."
+extracted[t].getType());
extracted[t].write(outimg);
outimg.flush();
outimg.close();
}
tbo = new WorkBookHandle();
sheet = tbo.getWorkSheet("Sheet1");
CellHandle a1 = sheet.add
("New workbook with 3 images: a gif, a jpg, and a png", "A1");

// get gif image input stream


FileInputStream fin = new FileInputStream
(workingdir + "testImages.gif");

// add to sheet
ImageHandle giffy = new ImageHandle(fin, sheet);

// set picture size and location in sheet


giffy.setBounds(100, 100, 400, 200);
giffy.setName("giffy");
sheet.insertImage(giffy);

// add to sheet
for(int x=0;x<100;x++) {
fin = new FileInputStream(workingdir + "testImages.png");
ImageHandle jpgy = new ImageHandle(fin, sheet);
jpgy.setName("heart" + x);
// set the random x/y coords of picture
int ix = Math.round((float)((x * (Math.random()*10))));
jpgy.setX(100 + ix);
ix = Math.round((float)((x * (Math.random()*10))));
jpgy.setY(100 + ix);
sheet.insertImage(jpgy);
}
// get png image input stream
fin = new FileInputStream(workingdir + "testImages.jpg");
// add to sheet
ImageHandle pngy = new ImageHandle(fin, sheet);
// set just the x/y coords of picture
pngy.setX(10);
pngy.setY(200);
sheet.insertImage(pngy);
}
catch(Exception e){
System.err.println("testImages failed: " + e.toString());
}
testWrite(tbo, workingdir + "testImagesOut.xls");
WorkBookHandle newbook = new WorkBookHandle
(workingdir + "testImagesOut.xls",0);
System.out.println("Successfully read: " + newbook);
}

public void testWrite(WorkBookHandle b, String fout){


try{
java.io.File f = new java.io.File(fout);
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bbout = new BufferedOutputStream(fos);
bbout.write(b.getBytes());
bbout.flush();
fos.close();
}
catch (java.io.IOException e){
System.err.println("IOException in Tester. "+e);
}
}

See also this HowTo for a way to create a simple XLS without any additional library.

Das könnte Ihnen auch gefallen