A POI operation class that implements the export function

Source: Internet
Author: User

public class Exportexcel<t> {
public void Exportexcel (collection<t> DataSet, outputstream out) {
Exportexcel ("Test POI Export Excel document", NULL, DataSet, out, "yyyy-mm-dd");
}



public static void Main (string[] args) {
try {
String path2 = "D://123.png";
list<user> bs = new arraylist<user> ();
User U = new user ();
U.setloginname (Qrcodeutil.getrnnumber () + "");
U.setqrcodepath (path2);
Bs.add (U); Bs.add (U); Bs.add (U); Bs.add (U);

String Path = "e://";

Export Excel
OutputStream out2 = new FileOutputStream (Path+qrcodeutil.getrnnumber () + ". xls");

String[] headers = {"User name", "QR Code"};
list<string> exportfile = new arraylist<string> ();
Exportfile.add ("LoginName"); Exportfile.add ("Qrcodepath");

exportexcel<user> export = new exportexcel<user> ();
Export.exportexcel ("QR Code", headers, Bs,exportfile, Out2, "yyyy");

Out2.close ();
Joptionpane.showmessagedialog (NULL, "Export succeeded!");
SYSTEM.OUT.PRINTLN ("Excel Export succeeded! ");
System.exit (0);
} catch (Exception e) {
E.printstacktrace ();
}
}

/** inserting a picture into Excel
* @param datasheet The worksheet to be inserted
* @param col image starts from this column
* @param row image starts from this line
* The number of columns @param the width picture
* The number of rows @param height picture takes
* @param imgfile The picture file to insert
*/
public static void Insertimg (Writablesheet datasheet, int col, int row, int width,
int height, File imgfile) {
Writableimage img = new Writableimage (col, row, width, height, imgfile);
Datasheet.addimage (IMG);
}

@SuppressWarnings ("Unchecked")
public void Exportexcel (String title, string[] headers,
List<t> dataset,list<string> Exportfile, outputstream out, String pattern) {
Declaring a working book
Hssfworkbook workbook = new Hssfworkbook ();
Create a table
Hssfsheet sheet = workbook.createsheet (title);
Set table Default column width is 15 bytes
Sheet.setdefaultcolumnwidth ((short) 15);
Build and set another style
Hssfcellstyle style2 = Workbook.createcellstyle ();
Style2.setverticalalignment (Hssfcellstyle.vertical_top);

Declaring a paint top-level manager
Hssfpatriarch Patriarch = Sheet.createdrawingpatriarch ();

Generate table header row
Hssfrow row = sheet.createrow (0);
for (short i = 0; i < headers.length; i++) {
Hssfcell cell = Row.createcell (i);
hssfrichtextstring Text = new hssfrichtextstring (headers[i]);
Cell.setcellvalue (text);
}

Iterating through the collection data, producing rows of data
Iterator<t> it = Dataset.iterator ();
int index = 0;
while (It.hasnext ()) {index++;
row = Sheet.createrow (index);
T t = (t) it.next ();
int j = 0;
for (short i = 0; i < exportfile.size (); i++) {
try {
String name = Exportfile.get (i);
Object value = Beanutils.getproperty (t, name);
Hssfcell cell = Row.createcell (j);
Cell.setcellstyle (Style2);
j + +;
Coercion type conversion After judging the type of the value
String TextValue = null;
/*if (value instanceof Date) {
Date date = (date) value;
SimpleDateFormat SDF = new SimpleDateFormat (pattern);
TextValue = Sdf.format (date);
} else {*/
Other data types are simple to handle as strings
if (null! = value)
TextValue = Value.tostring ();
//}
If it is not picture data, use regular expressions to determine whether the TextValue are all made up of numbers
if (TextValue! = null) {
Pattern p = pattern.compile ("^//d+ (//.//d+)? $");
Matcher Matcher = P.matcher (TextValue);
if (Matcher.matches ()) {
is a number treated as double
Cell.setcellvalue (Double.parsedouble (TextValue));
}else if (name.equals ("Qrcodepath")) {
The property named Qrcodepath is the picture path information
Bytearrayoutputstream bytearrayout = new Bytearrayoutputstream ();
BufferedImage bufferimg = Imageio.read (new File (TextValue));
Imageio.write (bufferimg, "PNG", bytearrayout);
When there is a picture, set the row height to 327px;
Row.setheightinpoints (327);
Set the image column width to 195px, note a conversion of the unit here
Sheet.setcolumnwidth (i, (short) (40 * 195));
Sheet.autosizecolumn (i);
Hssfclientanchor anchor = new Hssfclientanchor (0, 0, 680, up, (short) I, Index, (short) I, index);
Hssfpicture pic = patriarch.createpicture (anchor, Workbook.addpicture (Bytearrayout.tobytearray (), Hssfworkbook.picture_type_png));
Pic.resize ();
}else {
hssfrichtextstring richstring = new hssfrichtextstring (TextValue);
Hssffont Font3 = Workbook.createfont ();
Font3.setcolor (HSSFColor.BLACK.index);
Richstring.applyfont (FONT3);
Cell.setcellvalue (richstring);
}
}
} catch (Exception e) {
E.printstacktrace ();
} finally {

}
}

}
try {
Workbook.write (out);
} catch (IOException e) {
E.printstacktrace ();
}

}

/**
* Create a single sheet
*
* @param sheetname
* Exported sheet name
* @param headers
* column Header
* @param DataSet
* Data to be exported
* @param exportfile
* required fields for export
* @param response
* @throws ioexception
*/
public void Exportexcel (String sheetname, string[] headers,
collection<t> DataSet, list<string> Exportfile,
HttpServletResponse response) throws IOException {
OutputStream out = null;
Response.setcontenttype ("application/vnd.ms-excel");

Response.setcharacterencoding ("GBK");
Response.setheader ("Content-disposition", "Attachment;filename="
+ New String (Sheetname.getbytes ("GBK"), "iso-8859-1") + ". xls");
out = Response.getoutputstream ();
Hssfworkbook workbook = new Hssfworkbook ();
Createsheet (SheetName, headers, DataSet, Exportfile, Out, "Yyyy-mm-dd",
Workbook);
try {
Workbook.write (out);
} catch (IOException e) {
E.printstacktrace ();
}
Out.flush ();
Out.close ();
}

/**
* Create multiple sheet
*
* @param title
* File name
* @param headermap
* With sheet named key, column header is value
* @param dataMap
* With sheet named key, data set is value
* @param cellmap
* With sheet named key, data is listed as value
* @param response
* @throws IOException
*/
public void Exportexcel (String title, map<string, Object> Headermap,
Map<string, object> DataMap, map<string, object> Cellmap,
HttpServletResponse response) throws IOException {
OutputStream out = null;
Response.setcontenttype ("application/vnd.ms-excel");
Response.setcharacterencoding ("GBK");
Response.setheader ("Content-disposition", "Attachment;filename="
+ New String (Title.getbytes ("GBK"), "iso-8859-1") + ". xls");
out = Response.getoutputstream ();
Hssfworkbook workbook = new Hssfworkbook ();
For (String Key:headerMap.keySet ()) {
String sheetname = key;
string[] headers = (string[]) headermap.get (key);
Collection<t> DataSet = (collection<t>) datamap.get (key);
List<string> exportfile = (list<string>) cellmap.get (key);
Createsheet (SheetName, headers, DataSet, Exportfile, out,
"Yyyy-mm-dd HH:mm:ss", workbook);
}
try {
Workbook.write (out);
} catch (IOException e) {
E.printstacktrace ();
}
Out.flush ();
Out.close ();
}

/**
* This is a common method, using the reflection mechanism of Java, can be placed in the Java collection and symbols of certain conditions of the data in the form of Excel output to the specified IO device
*
* @param sheetname
* Form sheet name
* @param headers
* Table attribute column an array group
* @param DataSet
* The collection of data that needs to be displayed, be sure to place objects that conform to the JavaBean style class. This method supports the
* The data type of the JavaBean attribute has basic data type and string,date,byte[] (picture data)
* @param out
* The stream object associated with the output device, you can export the Excel document to a local file or a network
* @param pattern
* If there is time data, set the output format. The default is "Yyy-mm-dd"
* @param workbook
* Declare a working book
*/
public void Createsheet (String sheetname, string[] headers,
collection<t> DataSet, List<string> Exportfile, outputstream out,
String pattern, Hssfworkbook workbook) {
Create a table
Hssfsheet sheet = workbook.createsheet (sheetname);
Set table Default column width is 15 bytes
Sheet.setdefaultcolumnwidth ((short) 15);
Declaring a paint top-level manager
Hssfpatriarch Patriarch = Sheet.createdrawingpatriarch ();
/*
*//define the size and location of annotations, see document hssfcomment comment = patriarch.createcomment (new
* Hssfclientanchor (0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); Set comment content
* Comment.setstring (New hssfrichtextstring ("You can add comments to the POI!) ")); //
* Set the comment author, when the mouse moves to the cell is available in the status bar to see the content. Comment.setauthor ("Leno");
*/
Generate table header row
Hssfrow row = sheet.createrow (0);
for (short i = 0; i < headers.length; i++) {
Hssfcell cell = Row.createcell (i);
Cell.setcellstyle (style);
hssfrichtextstring Text = new hssfrichtextstring (headers[i]);
Cell.setcellvalue (text);
}
Iterating through the collection data, producing rows of data
Iterator<t> it = Dataset.iterator ();
int index = 0;
Set cell contents on top
Hssfcellstyle style = Workbook.createcellstyle ();
Style.setverticalalignment (Hssfcellstyle.vertical_top);
while (It.hasnext ()) {
index++;
row = Sheet.createrow (index);
T t = (t) it.next ();
int j = 0;
for (short i = 0; i < exportfile.size (); i++) {
try {
String name = Exportfile.get (i);
Object value = Beanutils.getproperty (t, name);
Hssfcell cell = Row.createcell (j);
Cell.setcellstyle (style);
j + +;
Coercion type conversion After judging the type of the value
String TextValue = null;
/*if (value instanceof Date) {
Date date = (date) value;
SimpleDateFormat SDF = new SimpleDateFormat (pattern);
TextValue = Sdf.format (date);
} else {*/
Other data types are simple to handle as strings
if (null! = value)
TextValue = Value.tostring ();
//}
If it is not picture data, use regular expressions to determine whether the TextValue are all made up of numbers
if (TextValue! = null) {
Pattern p = pattern.compile ("^//d+ (//.//d+)? $");
Matcher Matcher = P.matcher (TextValue);
if (Matcher.matches ()) {
is a number treated as double
Cell.setcellvalue (Double.parsedouble (TextValue));
}else if (name.equals ("Qrcodepath")) {//property named Qrcodepath is the picture path information
Bytearrayoutputstream bytearrayout = new Bytearrayoutputstream ();
BufferedImage bufferimg = Imageio.read (new File (TextValue));
Imageio.write (bufferimg, "PNG", bytearrayout);
When there is a picture, set the row height to 327px; Adjust height to 120
Row.setheightinpoints (120);
Set the image column width to 195px, note a conversion of the unit here
Sheet.setcolumnwidth (i, (short) (40 * 195));
Sheet.autosizecolumn (i);
Hssfclientanchor anchor = new Hssfclientanchor (0, 0, 680, up, (short) I, Index, (short) I, index);
Hssfpicture pic = patriarch.createpicture (anchor, Workbook.addpicture (Bytearrayout.tobytearray (), Hssfworkbook.picture_type_png));
Pic.resize ();
} else {
hssfrichtextstring richstring = new Hssfrichtextstring (
TextValue);
Hssffont Font3 = Workbook.createfont ();
Font3.setcolor (HSSFColor.BLACK.index);
Richstring.applyfont (FONT3);
Cell.setcellvalue (richstring);
}
}
} catch (Exception e) {
E.printstacktrace ();
} finally {

}
}
}
}

}

A POI operation class that implements the export function

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.