Poi read Excel
Use poi to process Excel documents
Java Doc:
Http://jakarta.apache.org/poi/apidocs/index.html
Poi is an excellent Java open-source project dedicated to parsing and generating file types related to Microsoft OLE 2, such as Word and Excel.
Poi package always says:
Org. Apache. Poi. hssf. eventmodel processes various actions generated in reading and writing Excel documents.
Org. Apache. Poi. hssf. eventusermodel provides various classes for reading Excel documents.
Org. Apache. Poi. hssf. Record. Formula contains the formula processing class, which is used in the Excel document.
Org. Apache. Poi. hssf. usermodel contains various classes for generating Excel documents.
Org. Apache. Poi. hssf. util provides tools for processing attributes of Excel documents.
Output Excel document
First, create an hssfworkbook object.
Get an hssfsheet object from the hssfworkbook object. Note that this is the only way you can get the worksheet object from the workbook object.
There is no common constructor for the worksheet object. This is because in the Excel model, the worksheet object cannot exist independently of the workbook.
Similarly, you can obtain the hssfrow object from the worksheet object and the hssfcell object from the hssfrow object. Each type depends on it.
.
To create a table header, use the region object to create a merging area for rows and columns. Note that rows and columns are both based on 0.
Use the setcellvalue method of the hssfcell object to set data for cells. The cell supports all Java local objects such as string and Int. The API also supports
Other commonly used data types.
The hssfstyle class in hssf processes all attributes related to cell display, such as color, Font, height, and width. You can create a relative for a specific cell object.
For complex attributes such as font and color, hssffont and hssfcolor objects are also provided.
Cells support formulas.
Finally, to create an Excel file physically on the file system, you need to call the write method from the hssfworkbook object and pass the outputstream object.
Input Excel document
Hssf provides a special poifsfilesystem object to specifically read Microsoft OLE 2 objects. Using poifsfilesystem objects, you
Construct an hssfworkbook object in the Excel document.
Use Java in web applications to access Excel objects
Use the mime-type string "application/vnd. MS-excel"
In the response header, how does the content-Disposition entry distribute content to the browser? The Inline attribute indicates that the browser should prompt before opening this document
"Open/save/cancel" dialog box.
How to use a POI package
Http://jakarta.apache.org/builds/jakarta-poi/
There are 3 directories under realese-> bin-> poi-2.5.1-final-20040804.jar
After the file is unlocked, put the poi-2.5.1-final-20040804.jar
In jsk/lib/JRE/lib/EXT
Everything is OK !! Note: The original compressed package contains three file packages, which of the following packages are recommended?
There are two problems:
1. How to configure POI in Web Applications
2. Is there an example of reading an Excel file in JSP?
---------------------------------------------------------------
Put the POI. jar file in the WEB-INF/lib directory of your application and you can use it in this application.
---------------------------------------------------------------
1. Put the poi package in the lib directory of web-INF.
2
Import org. Apache. Poi. hssf. usermodel. hssfworkbook;
Import org. Apache. Poi. hssf. usermodel. hssfsheet;
Import org. Apache. Poi. hssf. usermodel. hssfrow;
Import org. Apache. Poi. hssf. usermodel. hssfcell;
Import java. Io. fileinputstream;
Public class readxl {
/** Storage location of Excel files. Note that it is a forward slash */
Public static string filetoberead = "D:/jtest/gongye.xls ";
Public static void main (string argv []) {
Try {
// Create a reference to an Excel Workbook File
Hssfworkbook workbook = new hssfworkbook (New fileinputstream (filetoberead ));
// Create a reference to the worksheet.
// In this example, reference by name (let's assume that the table has the default name "sheet1 ")
Hssfsheet sheet = Workbook. getsheet ("sheet1 ");
// You can also use getsheetat (INT index) to reference data by index,
// In the Excel document, the default index of the first worksheet is 0,
// The statement is: hssfsheet sheet = Workbook. getsheetat (0 );
// Read the upper left Unit
Hssfrow ROW = sheet. getrow (0 );
Hssfcell cell = row. getcell (short) 0 );
// Output unit content. Cell. getstringcellvalue () is used to obtain the value of the unit.
System. Out. println ("upper left Unit:" + cell. getstringcellvalue ());
} Catch (exception e ){
System. Out. println ("xlread ():" + E );
}
}
}
========================================================== ========================================================== ========================================================== =
How to use Java poi to generate an Excel table file!
Publisher: [edit site] Source: [] Browse: [] Comment: [] Font: large, medium, and small
// Use Java poi
// Put the two jar files to LIB/EXT
// Code run against the jakarta-poi-1.5.0-FINAL-20020506.jar.
// And commons-logging-1.0.jar
Example program:
Import org. Apache. Poi. hssf. usermodel .*;
Import java. Io. fileoutputstream;
// Code run against the jakarta-poi-1.5.0-FINAL-20020506.jar.
// And commons-logging-1.0.jar
Public class poitest {
Static public void main (string [] ARGs) throws exception {
Fileoutputstream Fos = new fileoutputstream (D: // foo.xls );
Hssfworkbook WB = new hssfworkbook ();
Hssfsheet S = WB. createsheet ();
WB. setsheetname (0, matrix );
For (short I = 0; I <50; I ++ ){
Hssfrow ROW = S. createrow (I );
For (short J = 0; j <50; j ++ ){
Hssfcell cell = row. createcell (j );
Cell. setcellvalue (+ I ++, + J );
}
}
WB. Write (FOS );
FOS. Close ();
}
}
Application instance:
Implementation in Dao. hibernate
/**
* Import an Excel table
*/
Public list exceltodb (inputstream FL ){
List list = new arraylist ();
Workbook WB = NULL;
Try
{
WB = Workbook. getworkbook (FL );
} Catch (exception E)
{
System. Out. println ("aaaaaaaaaa:" + E. getmessage ());
}
Sheet rs = WB. getsheet (0 );
Int lastrownumber = Rs. getrows (); // obtain the number of rows
System. Out. println ("number of rows:" + lastrownumber );
For (INT I = 2; I <lastrownumber; I ++)
{
Int colnums = Rs. getcolumns (); // Number of Columns
String [] onerecoder = new string [colnums];
For (INT m = 0; m <colnums; m ++)
{
Cell c00 = Rs. getcell (M, I); // M indicates that column I is a row.
String strc00 = c00.getcontents ();
Onerecoder [m] = strc00;
}
Employegongzicard egzc = new employegongzicard ();
Egzc. setpeoplehao (onerecoder [0]); // employee ID
Egzc. setbumen (onerecoder [1]); // Department name
Egzc. setbumencode (onerecoder [2]); // department ID
Egzc. setpeoplename (onerecoder [3]); // name
Egzc. setpeopleshenfenzheng (onerecoder [4]); // ID card
Egzc. setokbankcard (onerecoder [5]); // card number
Egzc. setbanklei (onerecoder [6]); // card type
Egzc. setflags (0 );
Date dt = new date ();
Egzc. setdengjitime (DT );
// Egzc. setcontrolpeo ("");
If (! Ishavenpeogongzicard (onerecoder [0], onerecoder [2], onerecoder [6], 2 ))
{
Boolean B = saveemployegongzicard (egzc );
}
Else
{
List. Add (egzc); // cause of unsuccessful information: this type of card of the employee may exist and is not reported as a loss.
}
}
Return list;
}
Public Boolean ishavenpeogongzicard (string bianhao, string bumencode, string kaleixing, int flags ){
Boolean B = false;
List list = NULL;
Try {
List = This. gethibernatetemplate (). Find ("from employegongzicard where flags! = "+ Flags +" and bumencode = '"+ bumencode +"' and banklei = '"+ kaleixing +"' and peoplehao = '"+ bianhao + "'");
If (list! = NULL & list. Size ()> 0)
B = true;
} Catch (exception e ){
E. printstacktrace ();
}
Return B;
}
In struts
Public actionforward exceltodb (
Actionmapping mapping,
Actionform form,
Httpservletrequest request,
Httpservletresponse response)
{
Uploadexcelform = (uploadexcelform) form;
Formfile FF = uploadexcelform. getfexcel ();
System. Out. println ("the object to be loaded is:" + FF + "<End ");
Inputstream in = NULL;
Try {
In = ff. getinputstream ();
List list = maid. exceltodb (in );
Request. setattribute ("failedlist", list );
} Catch (filenotfoundexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
Return Mapping. findforward ("exceltodb ");
}
JSP page
<% @ Page Language = "Java" contenttype = "text/html; charset = GBK" pageencoding = "GBK" %>
<% @ Page import = "Java. util. *, persistent. employegongzicard" %>
<%
String Path = request. getcontextpath ();
List list = NULL;
If (request. getattribute ("failedlist ")! = NULL &&! Request. getattribute ("failedlist"). tostring (). Equals (""))
{
List = (list) request. getattribute ("failedlist ");
}
If (list = NULL)
{
List = new arraylist ();
}
%>
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = GBK">
<Title> payroll card import </title>
</Head>
<Body>
<Form action = "<% = PATH %>/gongzikadj. do? Message = exceltodb "enctype =" multipart/form-Data "method =" Post ">
<Table>
<Tr> <TD colspan = "2"> bank payroll data </TD> </tr>
<Tr> <TD colspan = "2"> Note: </TD> </tr>
<Tr> <TD colspan = "2"> 1. Excel file format, it must be "no. | employee No. | employee Department | employee name | ID card No. | card No. | card type" column 7. The first row is the default column name and data is ignored. </TD> </tr>
<Tr> <TD colspan = "2"> 2. If the value of the first column is null in the Data row of an Excel file, the end of the data is deemed to be complete, and the subsequent content is ignored. </TD> </tr>
<Tr> <TD colspan = "2"> 3. Update the existing salary card number to a new value by default.
</TD> </tr>
<Tr> <TD> select an Excel file: </TD> <input type = "file"/> </TD> </tr>
<Tr> <TD colspan = "2"> <input type = "Submit" value = "start to import data"/> </TD> </tr>
</Table>
</Form>
<%
If (list! = NULL & list. Size ()> 0 ){
%>
<Table>
<Tr> <TD colspan = "7"> list of employees who failed to import </TD> </tr>
<Tr> <TD colspan = "7"> each employee can have only one payroll card (not report loss) </TD> </tr>
<Tr> <TD colspan = "7"> cause: this employee's card type exists and the card status is not report loss </TD> </tr>
<Tr> <TD> employee ID </TD> <TD> employee Department </TD> <TD> department ID </TD> <TD> employee name </TD> <TD> ID card number </TD> <TD> card type </TD> </tr>
<%
Iterator it = List. iterator ();
While (it. hasnext ())
{
Employegongzicard egzc = new employegongzicard ();
Egzc = (employegongzicard) it. Next ();
%>
<Tr>
<TD> <% = egzc. getpeoplehao () = NULL? "": Egzc. getpeoplehao () %> </TD>
<TD> <% = egzc. getbumen () = NULL? "": Egzc. getbumen () %> </TD>
<TD> <% = egzc. getbumencode () = NULL? "": Egzc. getbumencode () %> </TD>
<TD> <% = egzc. getpeoplename () = NULL? "": Egzc. getpeoplename
<TD> <% = egzc. getpeoplename () = NULL? "": Egzc. getpeoplename () %> </TD>
<TD> <% = egzc. getpeopleshenfenzheng () = NULL? "": Egzc. getpeopleshenfenzheng () %> </TD>
<TD> <% = egzc. getokbankcard () = NULL? "": Egzc. getokbankcard () %> </TD>
<TD> <% = egzc. getbanklei () = NULL? "": Egzc. getbanklei () %> </TD>
</Tr>
<% }%>
</Table>
<% }%>
</Body>
</Html>