自行導入poi3.9的jar包
工具類:
package com.cpic.caf.template.home.util;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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;
/**
*
* @author librag
* @version v1.0
* @param <T>
* 應用泛型,代表任意一個符合javabean風格的類
* 注意這里為了簡單起見,boolean型的屬性xxx的get器方式為getXxx(),而不是isXxx()
* byte[]表jpg格式的圖片數據
*/
public class ExportExcel<T>{
public static final String Map = "Map";
public static final String List = "List";
private int List_Size = 0;
/*
public ExportExcel(int List_Size) {
this.List_Size = List_Size;
}
public ExportExcel() {
}*/
/**
* @param title
* 表格標題名
* @param headers
* 表格屬性列名數組
* @param dataset 允許的類型(實體類,List<List<Object>>,List<Map<String,Object>>)
* 需要顯示的數據集合,集合中一定要放置符合javabean風格的類的對象。此方法支持的
* javabean屬性的數據類型有基本數據類型及String,Date,byte[](圖片數據)
* @param out
* 與輸出設備關聯的流對象,可以將EXCEL文檔導出到本地文件或者網絡中
* @param pattern
* 如果有時間數據,設定輸出格式。默認為"yyy-MM-dd"
Controller示例
//引用瀏覽器引擎下載
//使用本工具類創建對象
ExportExcel<對象> ex = new ExportExcel<對象>();
//創建列
String[] headers =
{ "主鍵", "從業者ID", "案例是作品集還是婚禮案例", "案例類型", "標題","案例地址","描述","置頂","刪除狀態","訪問量","收藏量"};
//創建值列
List<對象> dataset = Service.方法名();
//調用工具類對象
ex.exportExcel(headers,dataset,response);
//提示
System.out.println("excel導出成功!");
Controller示例2
//直接下載到本地磁盤
//使用本工具類創建對象
ExportExcel<Map<String, Object>> ex = new ExportExcel<對象>();
//創建列
String[] headers =
{ "主鍵", "從業者ID", "案例是作品集還是婚禮案例", "案例類型", "標題","案例地址","描述","置頂","刪除狀態","訪問量","收藏量"};
//創建值列
List<Map<String, Object>> dataset = Service.方法名();
//調用工具類對象
ex.exportExcel(headers,dataset,"E:\\文件夾名\\文件夾名");
//提示
System.out.println("excel導出成功!");
*/
/**
* 方法重載同時指向一個unchecked
* @param dataset Value列
* @param response 必須
* @param path (當傳入指定path時 方法會使用IO流下載到指定地址(文件夾) || 反之 會引用瀏覽器的下載引擎)
*/
public void exportExcel(Collection<T> dataset,String path){
exportExcel("EXCEL文檔", null, dataset, "yyyy-MM-dd",path);
}
public void exportExcel(String[] headers, Collection<T> dataset,String path) {
exportExcel("EXCEL文檔", headers, dataset, "yyyy-MM-dd",path);
}
public void exportExcel(String[] headers, Collection<T> dataset, String pattern,String path){
exportExcel("EXCEL文檔", headers, dataset, pattern,path);
}
public void exportExcel(Collection<T> dataset,HttpServletResponse response){
exportExcel("EXCEL文檔", null, dataset, "yyyy-MM-dd",response);
}
public void exportExcel(String[] headers, Collection<T> dataset,HttpServletResponse response) {
exportExcel("EXCEL文檔", headers, dataset, "yyyy-MM-dd",response);
}
public void exportExcel(String[] headers, Collection<T> dataset, String pattern,HttpServletResponse response){
exportExcel("EXCEL文檔", headers, dataset, pattern,response);
}
public void exportExcel(String[] headers, List<List<Object>> dataset,HttpServletResponse response) {
exportExcel("EXCEL文檔", headers, dataset, "yyyy-MM-dd",response);
}
public void MapExportExcel(String[] headers, List<Map<String, Object>> dataset,HttpServletResponse response) {
exportExcel("EXCEL文檔", headers, dataset, "yyyy-MM-dd",response,"Map");
}
/**
* 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符號一定條件的數據以EXCEL 的形式輸出到指定IO設備上
*
* @param title 表格標題名
* @param headers 表格屬性列名數組
* @param dataset 需要顯示的數據集合,集合中一定要放置符合javabean風格的類的對象。此方法支持的
* javabean屬性的數據類型有基本數據類型及String,Date,byte[](圖片數據)
* @param pattern 如果有時間數據,設定輸出格式。默認為"yyy-MM-dd"
*/
@SuppressWarnings("unchecked")
public void exportExcel(String title, String[] headers,Collection<T> dataset, String pattern,String path){
// 聲明一個工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一個表格
HSSFSheet sheet = workbook.createSheet(title);
// 設置表格默認列寬度為15個字節
sheet.setDefaultColumnWidth((short) 15);
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設置這些樣式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
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);
// 生成一個字體
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字體應用到當前的樣式
style.setFont(font);
// 生成並設置另一個樣式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一個字體
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字體應用到當前的樣式
style2.setFont(font2);
// 聲明一個畫圖的頂級管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定義注釋的大小和位置,詳見文檔
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
0, 0, 0, (short) 4, 2, (short) 6, 5));
// 設置注釋內容
comment.setString(new HSSFRichTextString("可以在POI中添加注釋!"));
// 設置注釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容.
comment.setAuthor("leno");
// 產生表格標題行
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);
}
try
{
// 遍歷集合數據,產生數據行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext())
{
index++;
row = sheet.createRow(index);
T t = (T) it.next();
// 利用反射,根據javabean屬性的先后順序,動態調用getXxx()方法得到屬性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++)
{
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[]
{});
Object value = getMethod.invoke(t, new Object[]
{});
// 判斷值的類型后進行強制類型轉換
String textValue = null;
/* if (value instanceof Integer) {
int intValue = (Integer) value;
cell.setCellValue(intValue);
} else if (value instanceof Float) {
float fValue = (Float) value;
textValue = new HSSFRichTextString(
String.valueOf(fValue));
cell.setCellValue(textValue);
} else if (value instanceof Double) {
double dValue = (Double) value;
textValue = new HSSFRichTextString(
String.valueOf(dValue));
cell.setCellValue(textValue);
} else if (value instanceof Long) {
long longValue = (Long) value;
cell.setCellValue(longValue);
}*/
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 byte[])
{
// 有圖片時,設置行高為60px;
row.setHeightInPoints(60);
// 設置圖片所在列寬度為80px,注意這里單位的一個換算
sheet.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
1023, 255, (short) 6, index, (short) 6, index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(
bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
}
else
{
// 其它數據類型都當作字符串簡單處理
textValue = value.toString();
}
// 如果不是圖片數據,就利用正則表達式判斷textValue是否全部由數字組成
if (textValue != null)
{
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches())
{
// 是數字當作double處理
cell.setCellValue(Double.parseDouble(textValue));
}
else
{
HSSFRichTextString richString = new HSSFRichTextString(
textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
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{
// 清理資源
}
//生成文件流
IOExcle(workbook,path);
}
/**
* (網絡傳輸)
* 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符號一定條件的數據以EXCEL 的形式輸出到指定IO設備上
* @param title 表格標題名
* @param headers 表格屬性列名數組
* @param dataset 需要顯示的數據集合,集合中一定要放置符合javabean風格的類的對象。此方法支持的
* javabean屬性的數據類型有基本數據類型及String,Date,byte[](圖片數據)
* @param pattern 如果有時間數據,設定輸出格式。默認為"yyy-MM-dd"
*/
@SuppressWarnings("unchecked")
public void exportExcel(String title, String[] headers,Collection<T> dataset, String pattern,HttpServletResponse response){
response.reset(); // 清除buffer緩存
// 指定下載的文件名
response.setHeader("Content-Disposition", "attachment;filename=contacts" + getDateTimeName() + ".xls");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 聲明一個工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一個表格
HSSFSheet sheet = workbook.createSheet(title);
// 設置表格默認列寬度為15個字節
sheet.setDefaultColumnWidth((short) 15);
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設置這些樣式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
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);
// 生成一個字體
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字體應用到當前的樣式
style.setFont(font);
// 生成並設置另一個樣式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一個字體
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字體應用到當前的樣式
style2.setFont(font2);
// 聲明一個畫圖的頂級管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定義注釋的大小和位置,詳見文檔
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
0, 0, 0, (short) 4, 2, (short) 6, 5));
// 設置注釋內容
comment.setString(new HSSFRichTextString("可以在POI中添加注釋!"));
// 設置注釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容.
comment.setAuthor("leno");
// 產生表格標題行
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);
}
try
{
// 遍歷集合數據,產生數據行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()){
index++;
row = sheet.createRow(index);
T t = (T) it.next();
// 利用反射,根據javabean屬性的先后順序,動態調用getXxx()方法得到屬性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++)
{
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[]
{});
Object value = getMethod.invoke(t, new Object[]
{});
// 判斷值的類型后進行強制類型轉換
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 byte[])
{
// 有圖片時,設置行高為60px;
row.setHeightInPoints(60);
// 設置圖片所在列寬度為80px,注意這里單位的一個換算
sheet.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
1023, 255, (short) 6, index, (short) 6, index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(
bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
}
else
{
// 其它數據類型都當作字符串簡單處理
textValue = value.toString();
}
// 如果不是圖片數據,就利用正則表達式判斷textValue是否全部由數字組成
if (textValue != null)
{
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches())
{
// 是數字當作double處理
cell.setCellValue(Double.parseDouble(textValue));
}
else
{
HSSFRichTextString richString = new HSSFRichTextString(
textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
}
}//while
}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{
// 清理資源
}
//生成文件流
HTTPExcle(workbook,response);
}
/**
* (網絡傳輸)集合
* 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符號一定條件的數據以EXCEL 的形式輸出到指定IO設備上
* @param title 表格標題名
* @param headers 表格屬性列名數組
* @param dataset 需要顯示的數據集合,集合中一定要放置符合javabean風格的類的對象。此方法支持的
* javabean屬性的數據類型有基本數據類型及String,Date,byte[](圖片數據)
* @param pattern 如果有時間數據,設定輸出格式。默認為"yyy-MM-dd"
*/
@SuppressWarnings("unchecked")
public void exportExcel(String title, String[] headers,List<List<Object>> dataset, String pattern,HttpServletResponse response){
response.reset(); // 清除buffer緩存
// 指定下載的文件名
response.setHeader("Content-Disposition", "attachment;filename=contacts" + getDateTimeName() + ".xls");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 聲明一個工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一個表格
HSSFSheet sheet = workbook.createSheet(title);
// 設置表格默認列寬度為15個字節
sheet.setDefaultColumnWidth((short) 15);
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設置這些樣式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
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);
// 生成一個字體
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字體應用到當前的樣式
style.setFont(font);
// 生成並設置另一個樣式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一個字體
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字體應用到當前的樣式
style2.setFont(font2);
// 聲明一個畫圖的頂級管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定義注釋的大小和位置,詳見文檔
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
0, 0, 0, (short) 4, 2, (short) 6, 5));
// 設置注釋內容
comment.setString(new HSSFRichTextString("可以在POI中添加注釋!"));
// 設置注釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容.
comment.setAuthor("leno");
// 產生表格標題行
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);
}
try {
for (int i = 0; i < dataset.size(); i++) {
//創建外層集合行
HSSFRow createRow = sheet.createRow(i+1);
for (int j = 0; j < dataset.get(i).size(); j++) {
createRow.createCell(j).setCellValue(dataset.get(i).get(j).toString());;
}
}
}catch (Exception e){
e.printStackTrace();
}finally{
// 清理資源
}
//生成文件流
HTTPExcle(workbook,response);
}
/**
* (網絡傳輸)集合Map
* 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符號一定條件的數據以EXCEL 的形式輸出到指定IO設備上
* @param title 表格標題名
* @param headers 表格屬性列名數組
* @param dataset 需要顯示的數據集合,集合中一定要放置符合javabean風格的類的對象。此方法支持的
* javabean屬性的數據類型有基本數據類型及String,Date,byte[](圖片數據)
* @param pattern 如果有時間數據,設定輸出格式。默認為"yyy-MM-dd"
*/
@SuppressWarnings("unchecked")
public void exportExcel(String title, String[] headers,List<Map<String, Object>> dataset, String pattern,HttpServletResponse response,String name){
response.reset(); // 清除buffer緩存
// 指定下載的文件名
response.setHeader("Content-Disposition", "attachment;filename=contacts" + getDateTimeName() + ".xls");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 聲明一個工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一個表格
HSSFSheet sheet = workbook.createSheet(title);
// 設置表格默認列寬度為15個字節
sheet.setDefaultColumnWidth((short) 15);
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設置這些樣式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
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);
// 生成一個字體
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字體應用到當前的樣式
style.setFont(font);
// 生成並設置另一個樣式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一個字體
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字體應用到當前的樣式
style2.setFont(font2);
// 聲明一個畫圖的頂級管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定義注釋的大小和位置,詳見文檔
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
0, 0, 0, (short) 4, 2, (short) 6, 5));
// 設置注釋內容
comment.setString(new HSSFRichTextString("可以在POI中添加注釋!"));
// 設置注釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容.
comment.setAuthor("leno");
// 產生表格標題行
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);
}
try {
dataset = nullToEmpty(dataset);
for (int i = 0; i < dataset.size(); i++) {
//創建外層集合行
HSSFRow createRow = sheet.createRow((i+1));
//第一種
Set<String> set = dataset.get(i).keySet(); //取出所有的key值
Iterator<String> it = set.iterator();
int j = 0;
while(it.hasNext()) {
/* String str = null;
if(it.next()!=null&&dataset.get(i)!=null&&dataset.get(i).get(it.next())!=null) {
System.out.println("----------------------------");
System.out.println(it.next());
System.out.println(dataset.get(i).get(it.next()));
str = dataset.get(i).get(it.next()).toString();
}*/
Object value = dataset.get(i).get(it.next());
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 byte[]){
// 有圖片時,設置行高為60px;
row.setHeightInPoints(60);
// 設置圖片所在列寬度為80px,注意這里單位的一個換算
sheet.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
1023, 255, (short) 6, (i+1), (short) 6, (i+1));
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(
bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
}else{
// 其它數據類型都當作字符串簡單處理
textValue = value.toString();
}
/*if(str!=null) {
}else {
createRow.createCell(j).setCellValue("");//取出元素
}
*/
// 如果不是圖片數據,就利用正則表達式判斷textValue是否全部由數字組成
if (textValue != null)
{
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches())
{
// 是數字當作double處理
createRow.createCell(j).setCellValue(Double.parseDouble(textValue));//取出元素
}
else
{
HSSFRichTextString richString = new HSSFRichTextString(
textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLACK.index);
richString.applyFont(font3);
createRow.createCell(j).setCellValue(richString);
}
}
j++;
}//判斷是否有下一個
}
}catch (Exception e){
e.printStackTrace();
}finally{
// 清理資源
}
//生成文件流
HTTPExcle(workbook,response);
}
/************************************************************(工具方法)***************************************************************/
public static void IOExcle(HSSFWorkbook workbook,String path) {
OutputStream out = null;
try {
out = new FileOutputStream(path.replaceAll("\\\\", "/")+getDateTimeName()+".xls");
workbook.write(out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}
public static void HTTPExcle(HSSFWorkbook workbook,HttpServletResponse response) {
OutputStream output;
try {
output = response.getOutputStream();
BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
bufferedOutPut.flush();
workbook.write(bufferedOutPut);
bufferedOutPut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getDateTimeName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String format = sdf.format(new Date());
return format;
}
/**
* <p>方法名:nullToEmpty</p>
* <p>功能描述:map的value如果是null處理成空字符串</p>
*/
public static List<Map<String, Object>> nullToEmpty(List<Map<String, Object>> list) {
if(list !=null && !list.isEmpty()) {
for(Map<String, Object> map : list) {
Set<String> set = map.keySet();
if(set != null && !set.isEmpty()) {
for(String key : set) {
if(map.get(key) == null) {
map.put(key, "");
}
}
}
}
}
return list;
}
}
使用
package com.cpic.caf.template.home.controller;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cpic.caf.template.home.business.ProtocolAppoint;
import com.cpic.caf.template.home.entity.OrderEO;
import com.cpic.caf.template.home.entity.ProtocolParam;
import com.cpic.caf.template.home.service.OrderService;
import com.cpic.caf.template.home.util.CommonFunction;
import com.cpic.caf.template.home.util.ExportExcel;
import com.cpic.caf.template.home.util.HomeSQLUtil;
import com.cpic.caf.template.home.util.OrderDSQLUtil;
import com.cpic.caf.workers.hall.entity.WorkUserEO;
import com.cpic.caf.workers.hall.entity.WorkersCaseuserEO;
import com.cpic.caf.workers.hall.service.OmnipotentSqlService;
import com.cpic.caf.workers.hall.service.WorkersCaseuserService;
/**
* 訂單
*
* Title: 喜事碼頭 Description: 例子 Copyright: Copyright (c) 2018
* Company:河南意萊享網絡科技有限公司
*
* @author changshenghui
* @version 1.1
* @Date 2018年6月12日
*/
@Controller
public class OrderController {
Logger logger = LoggerFactory.getLogger(OrderController.class);
@Autowired
OrderService orderService;
@Autowired
private OmnipotentSqlService omnipotent;
@Autowired
private WorkersCaseuserService WorkUserEO;
/**
* 獲得訂單信息列表(導出)
*
* @param model
* @param request
* @param pageRequest
* @return
*/
@RequestMapping(value = "/getEclise", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public void getOrderInfoList(Model model,HttpServletRequest request,HttpSession session,HttpServletResponse response) {
ExportExcel<Map<String, Object>> ex = new ExportExcel<Map<String, Object>>();
//創建列
String[] headers =
{ "主鍵", "從業者ID", "案例是作品集還是婚禮案例", "案例類型", "標題","案例地址","描述","置頂","刪除狀態","訪問量","收藏量",
"排序","剩余可上傳數","婚禮發生時間","創建時間","修改時間"};
//創建值列
List<Map<String, Object>> dataset = omnipotent.findsqlByParam("SELECT * FROM xsmt.ylx_workers_wuorder");
ex.MapExportExcel(headers,dataset,response);
System.out.println("excel導出成功!");
}
/**
* 獲得訂單信息列表
*
* @param model
* @param request
* @param pageRequest
* @return
*/
@RequestMapping(value = "/getOrderInfoList", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Map<String, Object> getOrderInfoList(Model model,
HttpServletRequest request,
HttpSession session,
@RequestParam(value="PageIndex",required=false)Integer PageIndex,
@RequestParam(value="paramIndex",required=false)Integer paramIndex,
@RequestParam(value="start",required=false)Integer start,
@RequestParam(value="NO",required=false)String NO,
@RequestParam(value="DateParam",required=false)String DateParam,
@RequestParam(value="BIZ",required=false)String BIZ
) {
try {
WorkUserEO attribute =(WorkUserEO) session.getAttribute("worker");//獲取登錄對象
Integer WU_id = 1;
String NO_ = "";
String SQL = null;
String SQLCount = null;
if(attribute == null) {
System.out.println("- 登錄對象為空 -");
}else {
WU_id = attribute.getId();
}
if(NO!=null) {
NO_ = NO;
}
logger.info("================================="+DateParam+"= 訂單查詢CYZid:"+WU_id+" into getOrderInfoList ==========================================");
Map<String, Object> map = new HashMap<String, Object>();
switch (paramIndex) {
case 1:
//查詢全部訂單
SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,null,null,null,NO_,DateParam,BIZ);
SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,null,null,null,NO_,DateParam,BIZ);
System.out.println("查詢全部訂單:"+SQL);
break;
case 2:
//查詢已支付
SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,1,null,null,null,NO_,DateParam,BIZ);
SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,1,null,null,null,NO_,DateParam,BIZ);
System.out.println("查詢已支付:"+SQL);
break;
case 3:
//查詢待處理
SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,5,null,null,NO_,DateParam,BIZ);
SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,5,null,null,NO_,DateParam,BIZ);
System.out.println("查詢待處理:"+SQL);
break;
case 4:
//查詢待已付款
SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,null,1,null,NO_,DateParam,BIZ);
SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,null,1,null,NO_,DateParam,BIZ);
System.out.println("查詢待已付款:"+SQL);
break;
case 5:
//查詢已完成
SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,6,null,null,NO_,DateParam,BIZ);
SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,6,null,null,NO_,DateParam,BIZ);
System.out.println("查詢已完成:"+SQL);
break;
case 6:
//查詢已取消
SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,null,null,1,NO_,DateParam,BIZ);
SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,null,null,1,NO_,DateParam,BIZ);
System.out.println("查詢已取消:"+SQL);
break;
default:
//查詢全部訂單
SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,null,null,null,NO_,DateParam,BIZ);
SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,null,null,null,NO_,DateParam,BIZ);
System.out.println("查詢全部訂單:"+SQL);
break;
}
// 查詢數據
List<Map<String, Object>> findsqlByParam = omnipotent.findsqlByParam(SQL);
if(start !=null){
// 總條數
List<Map<String, Object>> findsqlByCount = omnipotent.findsqlByParam(SQLCount);
map.put("totalCount", findsqlByCount.get(0).get("count"));
}
map.put("resultList", findsqlByParam);
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 增加訂單信息
*
* @param model
* @param request
* @param pageRequest
* @return
*/
@RequestMapping(value = "/jsonAddOrderInfo", method = RequestMethod.POST)
@ResponseBody
public ProtocolParam addOrderInfo(Model model, HttpServletRequest request,
@RequestParam Map<String, Object> pageRequest) {
logger.info("======================================== JsonAddOrderInfo==================================");
// 獲得要添加的字段
try {
String no = URLDecoder.decode((String) pageRequest.get("no"),
"utf-8");// 訂單編號
String cust_name = URLDecoder.decode(
(String) pageRequest.get("custname"), "utf-8");// 客戶姓名
// 創建實體對象
OrderEO order = new OrderEO();
// 訂單編號
if (no != null && !"".equals(no)) {
order.setNo(CommonFunction.getRandomOrderNo());
}
// 客戶名稱
if (cust_name != null && !"".equals(cust_name)) {
order.setCust_name(cust_name);
}
// 生成流水號
order.setTrade_no(CommonFunction.GetNewOrderNo(no));
// 服務名稱
order.setService_name("中式");
order.setCreation_time(new Date());
// 調用方法
String str = HomeSQLUtil.homeOrderAddSQL(order);
int count = orderService.add(str);
// orderService.addOrderInfo(order);
if (count > 0) {
return ProtocolAppoint.succeed("新增成功", null, null);
}
return null;
} catch (UnsupportedEncodingException e) {
return ProtocolAppoint.error("新增失敗", null, null);
}
}
/**
* 刪除
*
* @param pageRequest
* @return
*/
@RequestMapping(value = "/JsonDelOrderInfo", method = RequestMethod.POST)
@ResponseBody
public ProtocolParam delOrderInfo(
@RequestParam Map<String, Object> pageRequest) {
logger.info("=============================== JsonDelOrderInfo ===============================");
try {
int id = Integer.parseInt(URLDecoder.decode(
(String) pageRequest.get("id"), "utf-8"));
String sql = HomeSQLUtil.homeDelOrderInfo(id);
int count = orderService.delete(sql);
if (count > 0) {
return ProtocolAppoint.merry(200, "成功", null, null);
}
return null;
} catch (Exception e) {
return ProtocolAppoint.error("失敗", null, null);
}
}
@RequestMapping(value="/ModifyOrderInfo",method=RequestMethod.POST)
@ResponseBody
public ProtocolParam modifyOrderInfo(@RequestParam Map<String, Object> pageRequest){
logger.info("============================= ModifyOrderInfo =========================================");
try {
int id=Integer.parseInt(URLDecoder.decode(
(String) pageRequest.get("id"), "utf-8"));
OrderEO order=new OrderEO();
order.setNo("NO201806201543");
order.setCust_name("青青");
order.setId(BigInteger.valueOf(id));
String sql=HomeSQLUtil.homeModifyOrderInfo(order);
int count =orderService.update(sql);
if(count>0){
return ProtocolAppoint.merry(200, "成功", null, null);
}
return null;
} catch (Exception e) {
return ProtocolAppoint.error("失敗", null, null);
}
}
}
