Java Export XLS Generic tool class

Source: Internet
Author: User
Tags dateformat

Java Export XLS Generic tool class

Package Org.rui. Util;import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.IOException;import Java.io.inputstream;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.Method;import Java.text.simpledateformat;import Java.util.arraylist;import Java.util.date;import Java.util.List;import Java.util.map;import Java.util.map.entry;import Org.apache.poi.hssf.usermodel.hssfcell;import Org.apache.poi.hssf.usermodel.hssfcellstyle;import Org.apache.poi.hssf.usermodel.hssffont;import Org.apache.poi.hssf.usermodel.hssfrow;import Org.apache.poi.hssf.usermodel.hssfsheet;import Org.apache.poi.hssf.usermodel.hssfworkbook;import org.apache.poi.hssf.util.hssfcolor;/** * Import xls table to convert data to data stream * * * @ Author Liangrui * * encodfilenmae = Java.net.URLEncoder.encode (tablename+ ". xls", * "Utf-8"); * Response.setcontenttype ("Application/vnd.ms-excel;charset=utf-8"); * Response.setheader ("content-disposition", "Attachment;fileName= "+ * encodfilenmae); * */public Class xlsutil{/** * Convert data to output stream * * @param sheetname * Sheet name * @param header * Header map * @  PARAM list * Data set * @param clz * Object byte code * @param dateformat * If date formatted date default YYYY-MM-DD * @return * @throws Exception */@SuppressWarnings ("Rawtypes") public static InputStream Getxlsio (String sheetname,map< String, string> header, list<object> List, Class clz,string dateformat) throws Exception{hssfworkbook wb = new HS Sfworkbook (); Hssfsheet sheet = wb.createsheet (sheetname);//Set table The default column width is 15 bytes sheet.setdefaultcolumnwidth (15); Hssfrow row = sheet.createrow (0);//Fourth step, create a cell, and set the value header to set the table header centered Hssfcellstyle style = Wb.createcellstyle (); Style.setalignment (Hssfcellstyle.align_center); Create a center format//Set these styles//Style.setfillforegroundcolor (HSSFColor.CORAL.index);//back//Style.setfillpattern ( Hssfcellstyle.solid_foreground);//Style.setborderbottom (Hssfcellstyle.border_thin);//Style.setBorderLeft ( HssfcellstyLe. Border_thin);//Style.setborderright (Hssfcellstyle.border_thin);//Style.setbordertop (Hssfcellstyle.border_thin) ;//Style.setalignment (Hssfcellstyle.align_center);//Generate a font Hssffont font = Wb.createfont (); Font.setcolor ( HSSFColor.RED.index); font.setfontheightinpoints (short); Font.setboldweight (hssffont.boldweight_bold);// Apply the font to the current style style.setfont (font); Hssfcell cell; list<string> tempsort = new arraylist<string> (); int cellindex = 0;for (entry<string, String> Es:header . EntrySet ()) {Tempsort.add (Es.getvalue ()); cell = Row.createcell (cellindex);//Create a cell and put the data Cell.setcellstyle (style ); Cell.setcelltype (hssfcell.cell_type_string);//Cell.setencoding (HSSFCELL.ENCODING_UTF_16);// Specify the Encoding Cell.setcellvalue (Es.getkey ()); Set value cellindex++;} if (list = null) {for (int i = 0; i < list.size (); ++i) {Object obj = clz.newinstance (); obj = List.get (i); row = Sheet.cr Eaterow (i + 1);//Create a row, starting from 0//based on V to find the method and get the value for (int r = 0; r < tempsort.size (); r++) {//Get the value of object value = GETMETHODVAlue (CLZ, obj, Tempsort.get (r)); String strvalue = Convertype (value, dateformat); cell = Row.createcell (r); Cell.setcellvalue (strvalue);}}} FileOutputStream fos = new FileOutputStream ("D:/tewst.xls"); Bytearrayoutputstream OS = new Bytearrayoutputstream ();//byte array output stream try{wb.write (OS);//write Byte output stream object is} catch (IOException e) { E.printstacktrace ();} Finally{if (OS! = null) {Os.close ();}} byte[] BArry = Os.tobytearray ();//Gets the byte array//writes the array bytes to the input stream object InputStream ISBA = new Bytearrayinputstream (BArry); return ISBA; }/** * Get values based on field * * @param CLZ * @param o * @param field * @return */@SuppressWarnings ("Rawtypes") public static Object get Methodvalue (Class clz, Object o, String field) throws Nosuchmethodexception, Securityexception,illegalaccessexception, Illegalargumentexception,invocationtargetexception{character Charss = Field.charat (0); field = Field.replaceFirst ( Charss.tostring (), Character.touppercase (CHARSS) + ""); System.out.println (field);//Get Value @suppresswarnings ("unchecked") Method GetMethod = Clz.getdeclareDmethod ("Get" + field, new class[] {}); Object value = Getmethod.invoke (o, new object[] {}); return value;} public static string Convertype (Object value, String dateformat) {string rresult = "";//if (value instanceof Integer)//{/ /int result = (Integer) value;//return result;////} else if (value instanceof float)//{//float result = (float) value ;//Return result;////} else if (value instanceof Double)//{//double result = (double) value;//return result;////} el  Se if (value instanceof long)//{//Long result = (long) value;//return result;//}//if (value instanceof Boolean)//{// Boolean result = (Boolean) value;//return result;////} elseif (value instanceof date) {Date date = (date) value;if ("". E Quals (DateFormat) | | NULL = = DateFormat) {DateFormat = "yyyy-mm-dd";} Illegalargumentexceptionsimpledateformat SDF = new SimpleDateFormat (dateformat); rresult = Sdf.format (date);} else if (value instanceof byte[]) {//} Else{return value + "";} return rresult;}}

Package Org.servlet;import Java.io.ioexception;import Java.io.inputstream;import java.io.outputstream;import Java.io.unsupportedencodingexception;import Java.text.simpledateformat;import Java.util.ArrayList;import Java.util.hashmap;import Java.util.list;import Java.util.map;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.utils.XlsUtil; Import Test. student;/** * Servlet Implementation class Expxls */@WebServlet ("/expxls") public class Expxls extends httpservlet{ Private static final Long Serialversionuid = 1l;/** * Default constructor. */public Expxls () {}protected void doget (httpservletrequest request,httpservletresponse response) throws Servletexception, Ioexception{dopost (request, response);} protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception, ioexception{ String tableName= "Report name"; try{map<string, string> m = new hashmap<string, string> (), M.put ("id", "id"), m.put ("name", "name") ; M.put ("Age", "ages"), M.put ("Birthday", "birth"); list<object> list = new arraylist<object> (); SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-dd"); Student user1 = new Student (1, "Zhang Sanhangshan Zhang 33", 16,df.parse ("1997-03-12")); Student user2 = new Student (2, "John Doe", +, Df.parse ("1996-08-12")); Student User3 = new Student (3, "Harry", +, Df.parse ("1985-11-12")); List.add (user1); List.add (User2); List.add (User3); I Nputstream is = Xlsutil.getxlsio ("Data Report", M, list, Student.class, ""); String encodfilenmae = ""; encodfilenmae = Java.net.URLEncoder.encode (tablename+ ". xls", "utf-8"); Response.setcontenttype ("Application/vnd.ms-excel;charset=utf-8"); Response.setheader ("Content-Disposition", " Attachment;filename= "+ encodfilenmae);//output stream outputstream OS = null;//bytearrayoutputstream os=null;int leng = 0;byte[] B Ytes = new byte[1024]; Cache buffertry{//Gets the output stream object//os = response.out; os=response.Getoutputstream ();//k Read while ((Leng = is.read (bytes)) > 0) {//start writing os.write (bytes, 0, Leng);}} catch (Exception e) {e.printstacktrace ();} finally{try{if (is! = null) {Is.close ();} if (OS! = null) {Os.close ();}} catch (IOException e) {e.printstacktrace ();}}} catch (Exception e) {e.printstacktrace ();}}}


Java Export XLS Generic tool class

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.