Java uses POI to generate Excel files

Source: Internet
Author: User

1. Maven Import POI Package:

  

<dependency>    <groupId>org.apache.poi</groupId>    <artifactid>poi-ooxml</ Artifactid>    <version>3.17</version></dependency>
Pom.xml

2. Create a new test data entity class:

  

 PackageCom.clz.testexportexcel; Public classExcelmodel {PrivateString name; Private intAge ; PrivateString Phone; PrivateString address;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString Getphone () {returnphone; }     Public voidSetphone (String phone) { This. Phone =phone; }     PublicString getaddress () {returnaddress; }     Public voidsetaddress (String address) { This. Address =address; }     PublicExcelmodel (String name,intAge , String phone, string address) {        Super();  This. Name =name;  This. Age =Age ;  This. Phone =phone;  This. Address =address; }     PublicExcelmodel () {Super(); }    }
Excelmodel

3. New Tool class and test

 PackageCom.clz.testexportexcel;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.OutputStream;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.apache.poi.hssf.usermodel.HSSFCell;ImportOrg.apache.poi.hssf.usermodel.HSSFCellStyle;ImportOrg.apache.poi.hssf.usermodel.HSSFFont;ImportOrg.apache.poi.hssf.usermodel.HSSFRow;ImportOrg.apache.poi.hssf.usermodel.HSSFSheet;ImportOrg.apache.poi.hssf.usermodel.HSSFWorkbook;Importorg.apache.poi.ss.usermodel.HorizontalAlignment;/*** Generate export Excel *@authorAdministrator **/ Public classTestexportexcel { Public Static voidMain (string[] args) {String exportfilename= "Testexcel.xls"; String Exportfilepath= "E:\\testexcel"; List<ExcelModel> Excelmodels =NewArraylist<excelmodel>(); Excelmodel em1=NewExcelmodel ("Zhang San", 18, "123456", "Shanghai"); Excelmodel em2=NewExcelmodel ("John Doe", 20, "456789", "Nanjing"); Excelmodel em3=NewExcelmodel ("Harry", 22, "987412", "Hangzhou");        Excelmodels.add (EM1);        Excelmodels.add (EM2);        Excelmodels.add (EM3); String Exportexcel=Exportexcel (Excelmodels, Exportfilepath, exportfilename);            System.out.println (Exportexcel); }        /*** Export Excel *@paramExcelmodel Data Entity class *@paramExportfilepath Export File path *@paramexportfilename Export File name *@returngenerate file path*/     Public StaticString Exportexcel (list<excelmodel>excelmodels, String Exportfilepath, String exportfilename) {String FileUrl=NULL; Hssfworkbook WB=NULL; OutputStream OS=NULL; Try {            //determines whether a folder exists, does not exist, and createsFile Filedir =NewFile (Exportfilepath); if(!filedir.exists ())            {Filedir.mkdirs (); }            /*** Generate Excel file*/            //The first step is to create a webbook that corresponds to an Excel fileWB =NewHssfworkbook (); //In the second step, add a sheet in WebBook that corresponds to the sheet in the Excel fileHssfsheet sheet = wb.createsheet ("User Information export"); //The third step is to add the No. 0 row of the table header to the sheetHssfrow row = Sheet.createrow ((int) 0); //Fourth step, create a cell, and set the value header to center the headerHssfcellstyle style =Wb.createcellstyle (); Style.setalignment (HorizontalAlignment.Center); //Center FormatHssffont Font =Wb.createfont (); Font.setcolor (hssffont.color_red);//HSSFColor.VIOLET.index//Font Color//apply a font to the current styleStyle.setfont (font); Hssfcell Cell=NULL; //table header (corresponds to entity class data one by one)String[] headers={"name", "Age", "phone", "address"};  for(inti=0;i) {cell= Row.createcell (( Short) (i);                Cell.setcellvalue (Headers[i]);            Cell.setcellstyle (style); }            //Write data to Excel             for(inti = 0; I < excelmodels.size (); i++) {Excelmodel em=Excelmodels.get (i); //Create a row (starting at the second row)row = Sheet.createrow ((int) i + 1); //Create columns and assign valuesRow.createcell (0). Setcellvalue (Em.getname ()); Row.createcell (1). Setcellvalue (Em.getage ()); Row.createcell (2). Setcellvalue (Em.getphone ()); Row.createcell (3). Setcellvalue (Em.getaddress ()); }            //Write FileFILEURL = Exportfilepath + File.separator +Exportfilename; OS=NewFileOutputStream (FILEURL);            Wb.write (OS);        Os.flush (); } Catch(Exception e) {e.printstacktrace (); } finally {            if(OS! =NULL) {                Try{os.close (); } Catch(IOException e) {e.printstacktrace (); }            }            if(WB! =NULL) {                Try{wb.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }        if(FileUrl! =NULL&&NewFile (FILEURL). Exists ()) {            returnFileUrl; }        return NULL; }    }
Testexportexcel

Java uses POI to generate Excel files

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.