import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpSession;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.cddgg.lianyoulw.utils.Arith;
/**
* Export Excel table
*
* @author wangbowen
*
* @Param <T> generic application, a representative of any class in line with javabean style
*/
public class ExportExcel<T> {
/**
* Export excel
* @Param footTitle foot title
* @Param dataset control data
* @Param out the output stream
* @Param session Session
*/
public void exportExcel(String footTitle,Collection<T> dataset, OutputStream out,HttpSession session) {
export(footTitle, null, dataset, out, "yyyy-MM-dd",session);
}
/**
* Export excel
* @Param footTitle foot title
* @Param headers header
* @Param dataset control data
* @Param out the output stream
* @Param session Session
*/
public void exportExcel(String footTitle, String[] headers, Collection<T> dataset,
OutputStream out,HttpSession session) {
export(footTitle, headers, dataset, out, "yyyy-MM-dd",session);
}
/**
* Export excel
* @Param footTitle foot title
* @Param headers header
* @Param dataset control data
* @Param out the output stream
* @Param pattern verification
* @Param session Session
*/
public void exportExcel(String footTitle,String[] headers, Collection<T> dataset,
OutputStream out, String pattern,HttpSession session) {
export(footTitle,headers, dataset, out, pattern,session);
}
/**
* General method utilizes reflection of JAVA, JAVA may be placed in a certain set of data symbols and outputs to the condition specified in the IO device in the form of EXCEL
*
* @param title
* Table title
* @param headers
* Table Properties column name array
* @param dataset
* Data to be displayed collection, the collection must be placed in line with the object javabean style class. This method of support
* Data type javabean attributes of basic data types and String, Date, byte [] (picture data)
* @param out
* Stream object associated with the output device, you can EXCEL export documents to a local file or network
* @param pattern
* If there is time data, setting the output format. The default is "yyy-MM-dd"
* @Param session Session
*/
public void export(String title, String[] headers,
Collection<T> dataset, OutputStream out, String pattern, HttpSession session) {
// declare a workbook
XSSFWorkbook book = new XSSFWorkbook();
// Create a table
XSSFSheet sheet = book.createSheet();
// Set default column width of the table is 30 bytes
sheet.setDefaultColumnWidth(25);
// declare a drawing of the top-level manager
XSSFDrawing patriarch = sheet.createDrawingPatriarch();
book.setSheetName (0, title); // Set the name of the first sheet
XSSFRow row = sheet.createRow((short) 0);
XSSFFont font = book.createFont();
// font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
font.setFontHeightInPoints ((short) 9); // set the font size
font.setFontName ( "Microsoft elegant black");
XSSFCellStyle style = book.createCellStyle();
style.setAlignment (XSSFCellStyle.ALIGN_CENTER); // aligned
style.setFont(font);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
XSSFCellStyle style2 = book.createCellStyle();
style2.setAlignment (XSSFCellStyle.ALIGN_CENTER); // aligned
style2.setBorderTop(XSSFCellStyle.BORDER_THIN);
style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style2.setBorderRight(XSSFCellStyle.BORDER_THIN);
style2.setFont(font);
for (short i = 0; i < headers.length; i++) {
XSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
XSSFRichTextString text = new XSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// Loop Data
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = (T) it.next();
// by the reflection, according to the order javabean properties, dynamic invocation getXxx () method to obtain the property value
Field[] fields = t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
XSSFCell cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();
// If fieldName is entered if there idCard
if(fieldName.equals("idCard")){
fieldName = fieldName.equals("idCard")?"IDCard":fieldName;
}
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
Class<? extends Object> tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
After a cast type determination value //
String textValue = null;
if (value instanceof Boolean) {
boolean bValue = (Boolean) value;
textValue = "男";
if (!bValue) {
textValue = "女";
}
} else if (value instanceof Date) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format (date);
}else if(value instanceof Double){
double value1 = Double.parseDouble(value.toString());
textValue = Arith.doubleTransform(value1);
}else if (value instanceof byte[]) {
When // pictures, set the row height to 60px;
row.setHeightInPoints(60);
// set the picture where the column width is 80px, pay attention to where a conversion unit
sheet.setColumnWidth(i, (short) (35.7 * 80));
byte[] bsValue = (byte[]) value;
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0,
1023, 255, (short) 6, index, (short) 6, index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, book.addPicture(
bsValue, XSSFWorkbook.PICTURE_TYPE_JPEG));
} else {
// determine whether the value is empty
if(value != null){
// other data types are treated as simple strings
textValue = value.toString();
}
}
// If not the picture data on the use of regular expressions to determine whether textValue comprised solely of digits
if (textValue != null) {
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matches matches = p.matcher (text, value);
if (matcher.matches()) {
// double as a digital processing
cell.setCellValue(Double.parseDouble(textValue));
} else {
XSSFRichTextString richString = new XSSFRichTextString(
textValue);
richString.applyFont(font);
cell.setCellValue(richString);
}
}
} catch (SecurityException e) {
e.printStackTrace ();
} catch (NoSuchMethodException e) {
e.printStackTrace ();
} catch (IllegalArgumentException e) {
e.printStackTrace ();
} catch (IllegalAccessException e) {
e.printStackTrace ();
} catch (InvocationTargetException e) {
e.printStackTrace ();
} finally {
// clean up resources
}
}
}
try {
book.write(out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace ();
}
}
}
Instructions:
ExportExcel<ContractVO> ex = new ExportExcel<ContractVO>();
// set list name
String [] headers = { "number", "employee name", "gender", "type of contract", "××× number", "dispatch"
"Dispatch Time", "contract start time", "end of the contract period," "contract period", "state contract", "contract name"};
// query the value of the export list names
List<ContractVO> dataset = contractExpireDmn.getContractMessage();
response.reset();
// set the file type generated
response.setContentType("application/vnd.ms-excel");
// Set header
response.setHeader ( "Content-disposition", "attachment; filename =" + new String (( "Unit contract early warning information") .getBytes ( "gbk"), "iso8859-1")
+ ".xlsx");
OutputStream os = response.getOutputStream();
// the incoming data export to Excel way inside
ex.exportExcel ( "unit staff contract Excel document", headers, dataset, os, session);