Java implementation of Excel data export

Source: Internet
Author: User

Java implements Excel data export:

Currently, there are two Jakarta poi and Java Excel Technologies that are commonly used to implement Java Import and export Excel.

Jakarta POI is a set of Java APIs for accessing Microsoft format documents. Jakarta POI has a number of components, including HSSF for manipulating Excel-formatted files and HWPF for manipulating word, and only the HSSF that are currently used to manipulate Excel are relatively mature in various components. Official Homepage Http://poi.apache.org/index.html,API Document Http://poi.apache.org/apidocs/index.html

Jakarta POI HSSF API component

HSSF (the component used to manipulate Excel) provides users with objects in the Rg.apache.poi.hssf.usermodel package, including Excel objects, styles and formatting, and auxiliary operations. There are several objects:

2.3 Basic Operation steps

First, to understand the organization of an Excel file, an Excel file corresponds to a workbook (Hssfworkbook), a workbook can have multiple sheet (hssfsheet) composition, A sheet is made up of multiple row (Hssfrow), and a row is made up of multiple cells (Hssfcell).

Basic Operation steps:

Here's an example of a dynamically generated Excel file:

1 //Create a Hssfworkbook object2Hssfworkbook WB =NewHssfworkbook ();3 //Create a Hssfsheet object4Hssfsheet sheet = wb.createsheet ("Sheet0");5 //Create a Hssfrow object6Hssfrow row = Sheet.createrow (0);7 //Create a Hssfcell object8Hssfcell Cell=row.createcell (0);9 //set the value of a cellTenCell.setcellvalue ("Chinese in Cell"); One //Output Excel File AFileOutputStream output=NewFileOutputStream ("D:\\workbook.xls"); - wkb.write (output); -Output.flush ();

HSSF read the file also use these objects, just the corresponding createxxx method into the GetXXX method can be. As long as the understanding of the principle, whether it is read or write or a specific format can be easily implemented, is so-called know it more to know its why.

2: To export an Excel application instance:

Please refer to: 53213130

3: Tool class for exporting tables:

Excelutil:

1   Public Static voidDownloadutil (httpservletresponse response, list<list<string>>data) {2         //file name-time stamp3         LongTimemillis =System.currenttimemillis ();4String name =long.tostring (timemillis);5         //format of the response file6Response.setcontenttype ("Application/vnd.ms-excel");7         //Create an Excel object8Hssfworkbook Workbook =NewHssfworkbook ();9 TenServletoutputstream OutputStream =NULL; One         Try { A             //transcoding to support Chinese file names -String Codedfilename =NewString (Name.getbytes ("GBK"), "Iso-8859-1"); -Response.setheader ("Content-disposition", "attachment;filename=" + Codedfilename + ". xls"); the             //To load data into a table: -             //Create an Excel table -Hssfsheet sheet = workbook.createsheet ("Sheet1"); -             //Traverse Data: +              for(inti = 0; I < data.size (); i++) { -                 //Take out a row of data +List<string> RowData =Data.get (i); A                 //Create a row atHssfrow row = Sheet.createrow (1); -                  for(intj = 0; J < Rowdata.size (); J + +) { -                     //Take out one of the data in a row -String str =Rowdata.get (j); -                     //Create a grid (column) for a row of a table -Hssfcell cell =Row.createcell (j); in                     //to load data into a table: - Cell.setcellvalue (str); to                 } +             } -OutputStream =Response.getoutputstream (); the Workbook.write (outputstream); *  $}Catch(Exception e) {Panax Notoginseng e.printstacktrace (); -System.out.println ("File download failed! "); the}finally { +             Try { A                 //Clear Cache the Outputstream.flush (); +                 //turn off the output stream - outputstream.close (); $}Catch(IOException e) { $ e.printstacktrace (); -             } -         } theSystem.out.println ("File download succeeded! "); -}

3-2: Convert the object to a string array:

Tool class:

1 /*2 * Convert Java objects to string arrays3      */4      Public StaticString[] Getvaluerow (Object Bean)throwsException {5       //using Reflection6         //get byte code:7Class<?> AClass =Bean.getclass ();8         //Get field:9field[] Declaredfields =aclass.getdeclaredfields ();Ten         intLength =declaredfields.length; Onestring[] row =NewString[length]; A         //To take a value from a field: -          for(inti=0;i<length;i++){ -Field Declaredfield =Declaredfields[i]; theString FieldName =declaredfield.getname (); -             //String methodName = "GetUserName"; -String methodName = "Get" +fieldname.substring (0,1). toUpperCase () + -Fieldname.substring (1); +Method GetUserName =Aclass.getmethod (methodName); -Object invoke =Getusername.invoke (bean); +String value= ""; A             if(invoke!=NULL){ atValue=string.valueof (invoke); -             } -row[i]=value; -         } -         returnRow; -}

Java implementation of Excel data export

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.