匯出複合表頭excel
阿新 • • 發佈:2018-12-18
Controller層程式碼:前端將id拼接成“idList”,傳入後臺。
@RequestMapping("settle/provinceSettlement/downloadProvince.do") public void downloadProvince(HttpServletRequest request, HttpServletResponse response, ModelMap model) { setRequestModelMap(request, model); String idString = request.getParameter("idList"); Map<String, Object> resultMap = new HashMap<String, Object>(); List<Integer> idList = new ArrayList<Integer>(); // 接收資料庫的查詢出的資料 List<ProvinceSettlementVO> provinceSettlementVOList = new ArrayList<ProvinceSettlementVO>(); if(idString != null && idString != "") { List<String> idListString = Arrays.asList(idString.split(",")); try { for (String id : idListString) { if (id != null) { idList.add(Integer.valueOf(id)); } } } catch (Exception e) { log.error("downloadProvince", e); resultMap.put("msg", "idConversionError"); AjaxResponseUtil.returnData(response, "json", resultMap); } // 查詢出的list provinceSettlementVOList = provinceSettlementService.selectListById(idList); } String folderName = DateUtil.date2Str(new java.util.Date(), "yyyyMMddHHmmss"); // 任意fileDir名字,此處用到ParamInfoCache String fileDir = ParamInfoCache.get("
[email protected]_UP_DIR")+folderName; HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = null; sheet = wb.createSheet("集團結算報表(省結算表)"); ProvinceSettlementExportExcel.getProvinceSettlementExportExcel(wb,sheet,provinceSettlementVOList); String excelName = DateUtil.date2Str(new java.util.Date(), "yyyyMMddHHmmss"); // 生成excel檔案 SettleGroupUtil.outputExcel(wb, fileDir+"/"+excelName+".xls"); SettleGroupUtil.exportExcel(wb, response, request, excelName); }
dataUtil中的date2Str
public static String date2Str(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
ProvinceSettlementExportExcel類
package xxx.utils; import xxx.entity.ProvinceSettlementVO; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.CellRangeAddress; import org.apache.poi.ss.usermodel.CellStyle; import java.util.ArrayList; import java.util.List; public class ProvinceSettlementExportExcel { static final float COMPARE_ZREO = 0.000001F; public static void getProvinceSettlementExportExcel(HSSFWorkbook wb, HSSFSheet sheet, List<ProvinceSettlementVO> list) { PoolSettleExportExcelUtils exportExcel = new PoolSettleExportExcelUtils( wb, sheet); // 建立列標頭LIST List<String> fialList = new ArrayList<String>(); fialList.add("序號"); fialList.add("省份"); fialList.add("結算賬期"); fialList.add("應結算金額"); fialList.add("調整金額"); fialList.add("實際結算金額"); fialList.add(""); fialList.add(""); // 計算該報表的列數 int number = fialList.size(); List<String> fialList2 = new ArrayList<String>(); fialList2.add(""); fialList2.add(""); fialList2.add(""); fialList2.add(""); fialList2.add(""); fialList2.add("價款"); fialList2.add("稅款"); fialList2.add("價稅合計"); // 給工作表列定義列寬(實際應用自己更改列數) for (int i = 0; i < number; i++) { sheet.setColumnWidth(i, 4000); } // 建立單元格樣式 HSSFCellStyle cellStyle = wb.createCellStyle(); // 指定單元格居中對齊 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定單元格垂直居中對齊 cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 指定當單元格內容顯示不下時自動換行 cellStyle.setWrapText(true); cellStyle.setBorderLeft(CellStyle.BORDER_MEDIUM); cellStyle.setBorderBottom(CellStyle.BORDER_MEDIUM); cellStyle.setBorderRight(CellStyle.BORDER_MEDIUM); cellStyle.setBorderTop(CellStyle.BORDER_MEDIUM); // 設定單元格字型 HSSFFont font = wb.createFont(); // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); font.setFontName("仿宋_GB2312"); font.setFontHeight((short) 240); cellStyle.setFont(font); HSSFRow row2 = sheet.createRow(0); // 設定行高 row2.setHeight((short) 1500); HSSFCell row2Cell = null; // 建立不同的LIST的列標題 for (int i = 0; i < number; i++) { row2Cell = row2.createCell(i); row2Cell.setCellStyle(cellStyle); row2Cell.setCellValue(new HSSFRichTextString(fialList.get(i) .toString())); } // 合併單元格 sheet.addMergedRegion(new CellRangeAddress(0, 0, 5, 7)); HSSFCell row3Cell = null; HSSFRow row3 = sheet.createRow(1); row3.setHeight((short) 800); for (int i = 0; i < number; i++) { row3Cell = row3.createCell(i); row3Cell.setCellStyle(cellStyle); row3Cell.setCellValue(new HSSFRichTextString(fialList2.get(i) .toString())); } // 合併單元格 sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0)); sheet.addMergedRegion(new CellRangeAddress(0, 1, 1, 1)); sheet.addMergedRegion(new CellRangeAddress(0, 1, 2, 2)); sheet.addMergedRegion(new CellRangeAddress(0, 1, 3, 3)); sheet.addMergedRegion(new CellRangeAddress(0, 1, 4, 4)); List<List<Object>> list2 = new ArrayList<List<Object>>(); // DecimalFormat df = new DecimalFormat("0.00"); for (ProvinceSettlementVO provinceSettlementVO : list) { List<Object> p = new ArrayList<Object>(); p.add(provinceSettlementVO.getId()); p.add(provinceSettlementVO.getProvinceName()); p.add(provinceSettlementVO.getPaymentDays()); p.add(provinceSettlementVO.getSettlementAmount()); p.add(provinceSettlementVO.getAdjustmentAmount()); p.add(provinceSettlementVO.getCostAmount()); p.add(provinceSettlementVO.getTaxAmount()); p.add(provinceSettlementVO.getFactSettlementAmount()); list2.add(p); } HSSFCell rowkCell = null; int k = 1; for (List<Object> list3 : list2) { HSSFRow rowk = sheet.createRow(1 + k); rowk.setHeight((short) 450); // 其他的略低 for (int i = 0; i < number; i++) { rowkCell = rowk.createCell(i); // rowkCell.setCellType(HSSFCell.CELL_TYPE_STRING); rowkCell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); HSSFDataFormat hSSFDataFormat = wb.createDataFormat(); cellStyle.setDataFormat(hSSFDataFormat.getFormat("0.00")); // 把數字格式化為 // 帶兩位小數的模式 if (list3.get(i) instanceof Double) { rowkCell.setCellValue((Double) list3.get(i)); } else { rowkCell.setCellValue(new HSSFRichTextString(String .valueOf(list3.get(i)))); } rowkCell.setCellStyle(cellStyle); } k++; } } }
PoolSettleExportExcelUtils 類
package xxx.common.utils;
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.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;
import org.apache.poi.hssf.util.Region;
//font.setFontHeight((short) 320); // 20大小 excel 20倍
@SuppressWarnings("deprecation")
public class PoolSettleExportExcelUtils {
private HSSFWorkbook wb = null;
private HSSFSheet sheet = null;
public PoolSettleExportExcelUtils(HSSFWorkbook wb, HSSFSheet sheet) {
super();
this.wb = wb;
this.sheet = sheet;
}
public HSSFSheet getSheet() {
return sheet;
}
public void setSheet(HSSFSheet sheet) {
this.sheet = sheet;
}
public HSSFWorkbook getWb() {
return wb;
}
public void setWb(HSSFWorkbook wb) {
this.wb = wb;
}
/**
* 建立通用EXCEL頭部
*
* @param headString
* 頭部顯示的字元
* @param colSum
* 該報表的列數
*/
public void createNormalHead(String headString, int colSum) {
HSSFRow row = sheet.createRow(0);
// 設定第一行
HSSFCell cell = row.createCell(0);
row.setHeight((short) 800);
// 定義單元格為字串型別
cell.setCellType(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(new HSSFRichTextString(headString));
// 指定合併區域
sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) colSum));
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定單元格居中對齊
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定單元格垂直居中對齊
cellStyle.setWrapText(false);// 指定單元格自動換行
// 設定單元格字型
HSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("仿宋_GB2312");
font.setFontHeight((short) 320); // 20大小 excel 20倍
cellStyle.setFont(font);
cellStyle.setWrapText(false);// 指定單元格自動換行
cell.setCellStyle(cellStyle);
}
/**
* 建立通用報表第二行
*
* @param params
* 統計條件陣列
* @param colSum
* 需要合併到的列索引
*/
public void createNormalTwoRow(String params, int colSum) {
HSSFRow row1 = sheet.createRow(1);
row1.setHeight((short) 500);
HSSFCell cell2 = row1.createCell(0);
cell2.setCellType(HSSFCell.ENCODING_UTF_16);
cell2.setCellValue(new HSSFRichTextString(params));
// 指定合併區域
sheet.addMergedRegion(new Region(1, (short) 0, 1, (short) colSum));
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT); // 指定單元格居中對齊
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定單元格垂直居中對齊
cellStyle.setWrapText(false);// 指定單元格自動換行
// 設定單元格字型
HSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("仿宋_GB2312");
font.setFontHeight((short) 240);
cellStyle.setFont(font);
cell2.setCellStyle(cellStyle);
}
/**
* 設定報表標題
*
* @param columHeader
* 標題字串陣列
*/
public void createColumHeader(String[] columHeader) {
// 設定列頭
HSSFRow row2 = sheet.createRow(2);
// 指定行高
row2.setHeight((short) 600);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定單元格居中對齊
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定單元格垂直居中對齊
cellStyle.setWrapText(true);// 指定單元格自動換行
// 單元格字型
HSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("仿宋_GB2312");
font.setFontHeight((short) 250);
cellStyle.setFont(font);
/*
* cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 設定單無格的邊框為粗體
* cellStyle.setBottomBorderColor(HSSFColor.BLACK.index); // 設定單元格的邊框顏色.
* cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
* cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);
* cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
* cellStyle.setRightBorderColor(HSSFColor.BLACK.index);
* cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
* cellStyle.setTopBorderColor(HSSFColor.BLACK.index);
*/
// 設定單元格背景色
cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
HSSFCell cell3 = null;
for (int i = 0; i < columHeader.length; i++) {
cell3 = row2.createCell(i);
cell3.setCellType(HSSFCell.ENCODING_UTF_16);
cell3.setCellStyle(cellStyle);
cell3.setCellValue(new HSSFRichTextString(columHeader[i]));
}
}
/**
* 建立內容單元格
*
* @param wb
* HSSFWorkbook
* @param row
* HSSFRow
* @param col
* short型的列索引
* @param align
* 對齊方式
* @param val
* 列值
*/
public void cteateCell(HSSFWorkbook wb, HSSFRow row, int col, short align,
String val) {
HSSFCell cell = row.createCell(col);
cell.setCellType(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(new HSSFRichTextString(val));
HSSFCellStyle cellstyle = wb.createCellStyle();
cellstyle.setAlignment(align);
cell.setCellStyle(cellstyle);
}
/**
* 建立合計行
*
* @param colSum
* 需要合併到的列索引
* @param cellValue
*/
public void createLastSumRow(int colSum, String[] cellValue) {
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定單元格居中對齊
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定單元格垂直居中對齊
cellStyle.setWrapText(true);// 指定單元格自動換行
// 單元格字型
HSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("仿宋_GB2312");
font.setFontHeight((short) 250);
cellStyle.setFont(font);
HSSFRow lastRow = sheet.createRow((short) (sheet.getLastRowNum() + 1));
HSSFCell sumCell = lastRow.createCell(0);
sumCell.setCellValue(new HSSFRichTextString("合計"));
sumCell.setCellStyle(cellStyle);
sheet.addMergedRegion(new Region(sheet.getLastRowNum(), (short) 0,
sheet.getLastRowNum(), (short) colSum));// 指定合併區域
for (int i = 2; i < (cellValue.length + 2); i++) {
sumCell = lastRow.createCell(i);
sumCell.setCellStyle(cellStyle);
sumCell.setCellValue(new HSSFRichTextString(cellValue[i - 2]));
}
}
}
// 生成excel檔案 SettleGroupUtil.outputExcel
package xxx.common.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import java.util.zip.ZipEntry;
//import java.util.zip.ZipOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.apache.log4j.Logger;
import com.opensymphony.oscache.util.StringUtil;
/**
* @Descrption: 集團報表類
* @author turner
* @time 2014-1-5 下午3:11:45
* @version:
* @Copyright:
*/
public final class SettleGroupUtil {
static final float COMPARE_ZERO = 0.000001F;
private static Logger log = Logger.getLogger(SettleGroupUtil.class);
/**
* 將存放在sourceFilePath目錄下的原始檔,打包成fileName名稱的ZIP檔案,並存放到zipFilePath。
*
* @param sourceFilePath
* 待壓縮的檔案路徑
* @param zipFilePath
* 壓縮後存放路徑
* @param fileName
* 壓縮後文件的名稱
* @return flag
*/
public static boolean fileToZip(String sourceFilePath, String zipFilePath,
String fileName) {
boolean flag = false;
File sourceFile = new File(sourceFilePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
if (sourceFile.exists() == false) {
log.info(sourceFilePath + "is not exist");
} else {
try {
File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
if (zipFile.exists()) {
log.info(zipFilePath + " exists:" + fileName + ".zip"
+ " file.");
} else {
File[] sourceFiles = sourceFile.listFiles();
if (null == sourceFiles || sourceFiles.length < 1) {
log.info(sourceFilePath
+ " not exists file. no need to uncompress.");
} else {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
zos.setEncoding("GBK");
byte[] bufs = new byte[1024 * 10];
for (int i = 0; i < sourceFiles.length; i++) {
// 建立ZIP實體,並新增進壓縮包
ZipEntry zipEntry = new ZipEntry(
sourceFiles[i].getName());
zipEntry.setUnixMode(644);
zos.putNextEntry(zipEntry);
// 讀取待壓縮的檔案並寫進壓縮包裡
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis, 1024 * 10);
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
zos.write(bufs, 0, read);
}
}
flag = true;
}
}
} catch (FileNotFoundException e) {
log.error("", e);
} catch (IOException e) {
log.error("", e);
} finally {
// 關閉流
try {
if (null != bis)
bis.close();
if (null != zos)
zos.close();
} catch (IOException e) {
log.error("", e);
}
}
}
return flag;
}
public static String date2String(Date date) {
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
return sf.format(date);
}
/**
* @desc: copy file from here to there.
* @param src
* @param dst
*/
public static void copyFile(String src, String dst) {
BufferedWriter bufferedWriter = null;
BufferedReader bufferedReader = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(dst));
bufferedReader = new BufferedReader(new FileReader(src));
String read = new String();
while ((read = bufferedReader.readLine()) != null) {
bufferedWriter.write(read + "\r\n");
// bufferedWriter.newLine();
}
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (Exception e1) {
log.error("", e1);
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (Exception e2) {
log.error("", e2);
}
}
}
}
public static void copyFileNew(String oldPath, String newPath) {
InputStream inStream = null;
FileOutputStream fs = null;
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { // 檔案存在時
inStream = new FileInputStream(oldPath); // 讀入原檔案
fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 位元組數 檔案大小
// System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
fs.flush();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (inStream != null)
inStream.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
if (fs != null)
fs.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
/**
* 遞迴查詢檔案
*
* @param baseDirName
* 查詢的資料夾路徑
* @param targetFileName
* 需要查詢的檔名
* @param fileList
* 查詢到的檔案集合
*/
public static void findFiles(String baseDirName, String targetFileName,
List fileList) {
/**
* 演算法簡述: 從某個給定的需查詢的資料夾出發,搜尋該資料夾的所有子資料夾及檔案,
* 若為檔案,則進行匹配,匹配成功則加入結果集,若為子資料夾,則進佇列。 佇列不空,重複上述操作,佇列為空,程式結束,返回結果。
*/
String tempName = null;
// 判斷目錄是否存在
File baseDir = new File(baseDirName);
if (!baseDir.exists() || !baseDir.isDirectory()) {
log.info("find file fail:" + baseDirName + " is not the directory.");
} else {
String[] filelist = baseDir.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(baseDirName + "/" + filelist[i]); // WINDOWS
// 為\\
// System.out.println(readfile.getAbsolutePath());
if (!readfile.isDirectory()) {
tempName = readfile.getName();
if (SettleGroupUtil.wildcardMatch(targetFileName, tempName)) {
// 匹配成功,將檔名新增到結果集
fileList.add(readfile.getAbsoluteFile());
}
} else if (readfile.isDirectory()) {
findFiles(baseDirName + "/" + filelist[i], targetFileName,
fileList);
}
}
}
}
/**
* 萬用字元匹配
*
* @param pattern
* 萬用字元模式
* @param str
* 待匹配的字串
* @return 匹配成功則返回true,否則返回false
*/
private static boolean wildcardMatch(String pattern, String str) {
int patternLength = pattern.length();
int strLength = str.length();
int strIndex = 0;
char ch;
for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) {
ch = pattern.charAt(patternIndex);
if (ch == '*') {
// 萬用字元星號*表示可以匹配任意多個字元
while (strIndex < strLength) {
if (wildcardMatch(pattern.substring(patternIndex + 1),
str.substring(strIndex))) {
return true;
}
strIndex++;
}
} else if (ch == '?') {
// 萬用字元問號?表示匹配任意一個字元
strIndex++;
if (strIndex > strLength) {
// 表示str中已經沒有字元匹配?了。
return false;
}
} else {
if ((strIndex >= strLength) || (ch != str.charAt(strIndex))) {
return false;
}
strIndex++;
}
}
return (strIndex == strLength);
}
/**
* 生成excel檔案
*
* @param wb
* @param fileName
*/
public static void outputExcel(HSSFWorkbook wb, String fileName) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(fileName));
wb.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 流方式輸入EXCEL檔案
*
* @param fileName
* 檔名
*/
public static void exportExcel(HSSFWorkbook wb,
HttpServletResponse response, HttpServletRequest request,
String excelName) {
OutputStream fOut = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel");
String agent = request.getHeader("User-Agent");
boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
if (!StringUtil.isEmpty(excelName)) {
if (isMSIE) {
excelName = java.net.URLEncoder.encode(excelName, "UTF8");
} else {
excelName = new String(excelName.getBytes("UTF-8"),
"ISO-8859-1");
}
}
response.setHeader("content-disposition", "attachment;filename="
+ excelName + ".xls");
fOut = response.getOutputStream();
wb.write(fOut);
fOut.flush();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最後生成的表格如下: