Java uses POI to generate Excel tables

Source: Internet
Author: User

The required jar package, as shown below

Write an Excel tool class Excelutils. java

Import Java.lang.reflect.field;import Java.util.iterator;import Java.util.list;import Org.apache.poi.hssf.usermodel.hssfcell;import Org.apache.poi.hssf.usermodel.hssfcellstyle;import Org.apache.poi.hssf.usermodel.hssfdataformat;import Org.apache.poi.hssf.usermodel.hssfrow;import Org.apache.poi.hssf.usermodel.hssfsheet;import Org.apache.poi.hssf.usermodel.hssfworkbook;public class ExcelUtils {/** * Export Excel * @param headername (Excel column name) * @param headerkey (Export object property name) * @param sheetname (Excel page signed) * @param Datali St (exported data) * @return */public static Hssfworkbook createexcel (string[] headername, string[] Headerkey, String sheetname, L ist dataList) {try {if (headerkey.length <= 0) {return null;} if (datalist.size () <= 0) {return null;} Hssfworkbook wb = new Hssfworkbook (); Hssfsheet sheet;if ((sheetname = = null) | | (Sheetname.equals (""))) Sheet = Wb.createsheet ("Sheet1"), else {sheet = Wb.createsheet (sheetname);} Hssfrow row = sheet.createrow (0); Hssfcellstyle style = Wb.createcellstyle (); StYle.setalignment ((short) 2); Hssfcell cell = null;if (Headername.length > 0) {for (int i = 0; i < headername.length; i++) {cell = Row.createcell ( i); Cell.setcellvalue (Headername[i]); Cell.setcellstyle (style);}} int n = 0; Hssfcellstyle Contextstyle = Wb.createcellstyle (); Contextstyle.setdataformat (Hssfdataformat.getbuiltinformat ("#,# #0.00_);(#,# #0.00)); Hssfcellstyle contextstyle1 = Wb.createcellstyle (); Hssfdataformat format = Wb.createdataformat (); Contextstyle1.setdataformat (Format.getformat ("@")); Hssfcell cell0 = null; Hssfcell cell1 = null;for (Iterator localiterator = Datalist.iterator (); Localiterator.hasnext ();) {Object obj = Localiterator.next (); field[] fields = Obj.getclass (). Getdeclaredfields (), row = Sheet.createrow (n + 1); for (int j = 0; j < Headerkey.length; J + +) {if (headername.length <= 0) {cell0 = Row.createcell (j); Cell0.setcellvalue (Headerkey[j]); Cell0.setcellstyle ( style);} for (int i = 0; i < fields.length; i++) {if (Fields[i].getname (). Equals (Headerkey[j])) {fiElds[i].setaccessible (True), if (fields[i].get (obj) = = null) {Row.createcell (j). Setcellvalue (""); if (Fields[i].get (obj) instanceof number) {cell1 = Row.createcell (j); Cell1.setcelltype (0); Cell1.setcellstyle ( Contextstyle); Cell1.setcellvalue (double.parsedouble (Fields[i].get (obj). toString ()); break;} if ("". Equals (Fields[i].get (obj))) {cell1 = Row.createcell (j); Cell1.setcellstyle (contextstyle1); Row.createcell (j). Setcellvalue (""); Cell1.setcelltype (1); break;} Row.createcell (j). Setcellvalue (Fields[i].get (obj). toString ()); break;}}} n++;} for (int i = 0; i < headerkey.length; i++) {Sheet.setcolumnwidth (I, Headerkey[i].getbytes (). length*2*256);} Hssfworkbook LocalHSSFWorkbook1 = Wb;return LocalHSSFWorkbook1;} catch (Exception e) {e.printstacktrace (); return null;} finally {}}}

  

Add a Vo,studentvo.java

public class Studentvo {private int id;private string Sex;private string name;private string Grade;public string GetId () { return ID;} public void SetId (String id) {this.id = ID;} Public String Getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getgrade () {return grade;} public void Setgrade (String grade) {This.grade = grade;}}

In the Controller class, add the export Excel interface as follows

/** * National Network data Export * @param request * @param response */@RequestMapping ("/exportgwdatamanagelist") public void Exportgwdatamanag EList (HttpServletRequest request, httpservletresponse response) {try{list<studentvo> volist = new arraylist< Studentvo> (); Studentvo vo = new Studentvo (), Vo.setid ("1"), Vo.setsex ("male"), Vo.setname ("Zhang San"), Vo.setgrade ("Second Grade"), Volist.add (VO); vo = New Studentvo (), Vo.setid ("2"), Vo.setsex ("female"), Vo.setname ("John Doe"), Vo.setgrade ("First grade"), Volist.add (VO); vo = new Studentvo (); Vo.setid ("3"); Vo.setsex ("Male"), Vo.setname ("Harry"); Vo.setgrade ("Third grade"); Volist.add (VO); String[] Headername = {"Serial number", "Gender", "name", "Grade"}; String[] Headerkey = {"id", "Sex", "name", "Grade"}; Hssfworkbook wb = Excelutils.createexcel (Headername, Headerkey, "Year data Management", volist); if (WB = = null) {return;} Response.setcontenttype ("application/vnd.ms-excel"); SimpleDateFormat SDF = new SimpleDateFormat ("YYYYMMDDHHMMSS");D ate date = new Date (); String str = sdf.format (date); String fileName = "Student Information management" + Str;response.setheader ("content-dIsposition "," attachment;filename= "+ New String (Filename.getbytes (" gb2312 ")," iso-8859-1 ") +". xls "); outputstream Ouputstream = Response.getoutputstream (); Ouputstream.flush (); Wb.write (Ouputstream); Ouputstream.close ();} catch (Exception e) {e.printstacktrace ();}}

  

The page has only one generated Excel button, as shown below

Click the button to generate Excel, as shown below

Java uses POI to generate Excel tables

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.