Java writes data to an Excel file _demo

Source: Internet
Author: User
Tags getmessage object object

======= First Edition: basic ability realizes =======

ImportCom.google.common.collect.Maps;ImportOrg.apache.log4j.Logger;ImportOrg.apache.poi.hssf.usermodel.HSSFWorkbook;ImportOrg.apache.poi.ss.usermodel.*;ImportOrg.apache.poi.xssf.usermodel.XSSFWorkbook;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.OutputStream;ImportJava.util.Iterator;Importjava.util.List;ImportJava.util.Map;/*** Writes the contents of the read database to the Excel Template table for download needs*/ Public classWriterexcelfile {Private Static FinalLogger Logger = Logger.getlogger (writerexcelfile.class. GetName ()); /*** Write data to an Excel file under the specified path * There is a restriction: the order of the column names must be the same as the order in which the data is stored, otherwise it will cause confusion; This is the first edition, and later, to improve this *@parampath file storage paths *@paramName Sheet name *@paramstyle Excel Type *@paramTitles Title String *@paramvalues Content set *@returnt\f*/     Public Static BooleanGenerateworkbook (string path, string name, string style, list<string> titles, list<map<string, object> >values)        {Workbook Workbook; if("XLS". Equals (Style.touppercase ())) {Workbook=NewHssfworkbook (); } Else{Workbook=NewXssfworkbook (); }        //Create a tableSheet Sheet =Workbook.createsheet (name); //Set table Default column width is 15 bytesSheet.setdefaultcolumnwidth (( Short) 15); //Build Stylemap<string, cellstyle> styles =createstyles (Workbook); /** Create header row*/Row Row= Sheet.createrow (0);  for(inti = 0; I < titles.size (); i++) {cell cell=Row.createcell (i); Cell.setcellstyle (Styles.get ("Header"));        Cell.setcellvalue (Titles.get (i)); }        /** Write to Body*/Iterator<map<string, object>> iterator =Values.iterator (); intindex = 0;  while(Iterator.hasnext ()) {index++; Row=Sheet.createrow (index); Map<string, object> value =Iterator.next (); String content= "";  for(Map.entry<string, object>Map:value.entrySet ()) {Object Object=Map.getvalue (); Content=object.tostring (); }             for(inti = 0; I < value.size (); i++) {cell cell=Row.createcell (i); Cell.setcellstyle (Styles.get ("Cell"));            Cell.setcellvalue (content); }        }        /** Write to file*/        BooleanIscorrect =false; File File=NewFile (path); //If the file exists, delete the existing file and recreate a new copy of the        if(File.exists ()) {file.deleteonexit (); File=NewFile (path); } outputstream OutputStream=NULL; Try{OutputStream=Newfileoutputstream (file);            Workbook.write (OutputStream); Iscorrect=true; } Catch(IOException e) {logger.error (E.getmessage ()); } finally {            Try {                if(NULL!=OutputStream)                {Outputstream.close (); }            } Catch(IOException e) {logger.error (E.getmessage ()); }        }        returnIscorrect; }    /*** Create A library of cell styles*/    Private StaticMap<string, cellstyle>Createstyles (Workbook wb) {Map<string, cellstyle> styles =Maps.newhashmap (); DataFormat DataFormat=Wb.createdataformat (); //Heading stylesCellStyle TitleStyle =Wb.createcellstyle (); Titlestyle.setalignment (HorizontalAlignment.Center); //Horizontal AlignmentTitlestyle.setverticalalignment (Verticalalignment.center);//Vertical AlignmentTitlestyle.setlocked (true);        Titlestyle.setfillforegroundcolor (IndexedColors.BLUE.getIndex ());        Titlestyle.setfillbackgroundcolor (IndexedColors.YELLOW.getIndex ()); Font Titlefont=Wb.createfont (); Titlefont.setfontheightinpoints (( Short) 16); Titlefont.setbold (true); Titlefont.setfontname ("Microsoft Jas Black");        Titlestyle.setfont (Titlefont); Styles.put ("Title", TitleStyle); //File Header styleCellStyle HeaderStyle =Wb.createcellstyle ();        Headerstyle.setalignment (HorizontalAlignment.Center);        Headerstyle.setverticalalignment (Verticalalignment.center);        Headerstyle.setfillforegroundcolor (IndexedColors.GREY_50_PERCENT.getIndex ());        Headerstyle.setfillforegroundcolor (IndexedColors.LIGHT_BLUE.getIndex ());        Headerstyle.setfillpattern (Fillpatterntype.solid_foreground); Headerstyle.setwraptext (true); Font HeaderFont=Wb.createfont (); Headerfont.setfontheightinpoints (( Short) 12);        Headerfont.setcolor (IndexedColors.WHITE.getIndex ()); Titlefont.setfontname ("Microsoft Jas Black");        Headerstyle.setfont (HeaderFont); Styles.put ("Header", HeaderStyle); //Body StyleCellStyle CellStyle =Wb.createcellstyle ();        Cellstyle.setalignment (HorizontalAlignment.Center);        Cellstyle.setverticalalignment (Verticalalignment.center); Cellstyle.setwraptext (true);        Cellstyle.setborderright (Borderstyle.thin);        Cellstyle.setrightbordercolor (IndexedColors.BLACK.getIndex ());        Cellstyle.setborderleft (Borderstyle.thin);        Cellstyle.setleftbordercolor (IndexedColors.BLACK.getIndex ());        Cellstyle.setbordertop (Borderstyle.thin);        Cellstyle.settopbordercolor (IndexedColors.BLACK.getIndex ());        Cellstyle.setborderbottom (Borderstyle.thin);        Cellstyle.setbottombordercolor (IndexedColors.BLACK.getIndex ()); Styles.put ("Cell", CellStyle); returnstyles; }}
View Code

======= Shameless split-line =======

Java writes data to an Excel file _demo

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.