Excel讀寫工具類
緣起
在J2SE和J2EE應用程序開發中,經常會遇到上傳Excel,導出Excel的功能開發,對Excel的操作無非就是讀取Excel文件內容轉成javabean,或者是將javabean對象寫入Excel文件中。為了方便對Excel進行讀寫操作,可以將這塊代碼進行封裝,讀取Excel的操作封裝在ExcelReadKit,寫入Excel的操作封裝在ExcelWriteKit工具類中。
核心代碼
下面會寫出核心的java代碼,其中會用到apache poi 這個開源組建對Excel進行讀寫操作。
ExcelConfig.java
import org.apache.poi.ss.usermodel.Cell;
public class ExcelConfig {
// Excel文件輸出格式
public static final String FT_XLS = "xls";
public static final String FT_XLSX = "xlsx";
// Excel格數據類型
public static final int CT_NUMERIC = Cell.CELL_TYPE_NUMERIC;
public static final int CT_STRING = Cell.CELL_TYPE_STRING;
public static final int CT_BOOLEAN = Cell.CELL_TYPE_BOOLEAN;
public static final int CT_BLANK = Cell.CELL_TYPE_BLANK;
public static final int CT_FORMULA = Cell.CELL_TYPE_FORMULA;
}
ExcelReadResultBean.java
import java.util.List;
public class ExcelReadResultBean {
private boolean result = true;
private String errMsg = "";
private List<List<String>> contentList = null;
public boolean getResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public List<List<String>> getContentList() {
return contentList;
}
public void setContentList(List<List<String>> contentList) {
this.contentList = contentList;
}
}
ExcelWriteBean.java
package com.trendy.fw.common.excel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ExcelWriteBean {
String fileName = "";// 文件名,不帶后綴
String fileType = "";// 文件類型,xsl或xslx
String sheetName = "";// sheet名
List<String> headerList = new ArrayList<String>();// 表頭列表,可以為空
List<List<Object>> contentList = new ArrayList<List<Object>>();// 內容列表
HashMap<Integer, Integer> cellTypeMap = new HashMap<Integer, Integer>();// 表格類型,不填寫默認為字符串
HashMap<Integer, String> cellFormatMap = new HashMap<Integer, String>();// 表格格式,不填寫默認為字符串格式
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public List<String> getHeaderList() {
return headerList;
}
public void setHeaderList(List<String> headerList) {
this.headerList = headerList;
}
public List<List<Object>> getContentList() {
return contentList;
}
public void setContentList(List<List<Object>> contentList) {
this.contentList = contentList;
}
public HashMap<Integer, Integer> getCellTypeMap() {
return cellTypeMap;
}
public void setCellTypeMap(HashMap<Integer, Integer> cellTypeMap) {
this.cellTypeMap = cellTypeMap;
}
public void setCellType(int cellIndex, int cellType) {
cellTypeMap.put(cellIndex, cellType);
}
public HashMap<Integer, String> getCellFormatMap() {
return cellFormatMap;
}
public void setCellFormatMap(HashMap<Integer, String> cellFormatMap) {
this.cellFormatMap = cellFormatMap;
}
public void setCellFormat(int cellIndex, String cellFormat) {
cellFormatMap.put(cellIndex, cellFormat);
}
}
ExcelReadKit.java
package com.trendy.fw.common.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.trendy.fw.common.util.DateKit;
public class ExcelReadKit {
protected static Logger log = LoggerFactory.getLogger(ExcelReadKit.class);
/**
*
* @param filePath
* 文件路徑
* @param sheetIndex
* 第x個sheet
* @return
*/
public ExcelReadResultBean readExcel(String filePath, int sheetIndex) {
ExcelReadResultBean resultBean = new ExcelReadResultBean();
try {
Sheet sheet = null;
if (filePath.endsWith(ExcelConfig.FT_XLS)) {
FileInputStream fis = new FileInputStream(filePath); // 根據excel文件路徑創建文件流
POIFSFileSystem fs = new POIFSFileSystem(fis); // 利用poi讀取excel文件流
HSSFWorkbook wb = new HSSFWorkbook(fs); // 讀取excel工作簿
sheet = wb.getSheetAt(sheetIndex); // 讀取excel的sheet,0表示讀取第一個
} else {
OPCPackage pkg = OPCPackage.open(new File(filePath));
XSSFWorkbook wb = new XSSFWorkbook(pkg);// 讀取excel工作簿
sheet = wb.getSheetAt(sheetIndex); // 讀取excel的sheet,0表示讀取第一個
pkg.close();
}
resultBean = realSheetValue(sheet);
} catch (Exception e) {
log.error("[讀取Excel<{}>出錯]:", filePath, e);
resultBean.setResult(false);
resultBean.setErrMsg("讀取Excel文件出錯");
}
return resultBean;
}
/**
*
* @param fis
* 輸入的文件流
* @param sheetIndex
* 第x個sheet
* @return
*/
public ExcelReadResultBean readExcel(InputStream fis, int sheetIndex) {
ExcelReadResultBean resultBean = new ExcelReadResultBean();
try {
Sheet sheet = null;
Workbook wb = null;
try {
POIFSFileSystem fs = new POIFSFileSystem(fis); // 利用poi讀取excel文件流
wb = new HSSFWorkbook(fs); // 讀取excel工作簿
sheet = wb.getSheetAt(sheetIndex); // 讀取excel的sheet,0表示讀取第一個
} catch (Exception e) {
wb = new XSSFWorkbook(fis); // 讀取excel工作簿
sheet = wb.getSheetAt(sheetIndex); // 讀取excel的sheet,0表示讀取第一個
}
resultBean = realSheetValue(sheet);
wb.cloneSheet(sheetIndex);
fis.close();
} catch (Exception e) {
log.error("讀取Excel文件流時出錯:", e);
resultBean.setResult(false);
resultBean.setErrMsg("讀取Excel文件流出錯");
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
}
}
}
return resultBean;
}
private ExcelReadResultBean realSheetValue(Sheet sheet) {
ExcelReadResultBean resultBean = new ExcelReadResultBean();
boolean result = true;
String errMsg = "";
List<List<String>> list = new ArrayList<List<String>>();
int i = 0, j = 0;
for (i = 0; i <= sheet.getLastRowNum(); i++) {
try {
Row row = sheet.getRow(i); // 取出sheet中的某一行數據
if (row != null) {
List<String> rowList = new ArrayList<String>(row.getPhysicalNumberOfCells());
// 獲取該行中總共有多少列數據row.getLastCellNum()
for (j = 0; j < row.getLastCellNum(); j++) {
try {
Cell cell = row.getCell(j); // 獲取該行中的一個單元格對象
/*
* 當取某一行中的數據的時候,需要判斷數據類型,否則會報錯
* java.lang.NumberFormatException: You cannot get a
* string value from a numeric cell等等錯誤
*/
if (cell != null) {// 判斷cell是否為空
if (cell.getCellType() == ExcelConfig.CT_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 判斷是否日期類型
Date dateValue = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
rowList.add(DateKit.formatDate(dateValue, DateKit.DEFAULT_DATE_TIME_FORMAT));
} else {
rowList.add(String.valueOf(cell.getNumericCellValue()));
}
} else if (cell.getCellType() == ExcelConfig.CT_FORMULA) {// 讀取公式的值
try {
rowList.add(String.valueOf(cell.getNumericCellValue()));
} catch (IllegalStateException e) {
rowList.add(String.valueOf(cell.getRichStringCellValue()));
}
} else {
rowList.add(cell.getStringCellValue());
}
} else {// 如果cell為空,用空格字段代替
rowList.add("");
}
} catch (Exception e) {
log.error("讀取{}行{}列時出錯", i + 1, j + 1);
result = false;
errMsg = errMsg + "讀取" + (i + 1) + "行" + (j + 1) + "列時出錯;";
rowList.add("");
}
}
list.add(rowList);
}
} catch (Exception e) {
log.error("讀取{}行時出錯", i + 1);
result = false;
errMsg = errMsg + "讀取" + (i + 1) + "行時出錯";
}
}
resultBean.setResult(result);
resultBean.setErrMsg(errMsg);
resultBean.setContentList(list);
return resultBean;
}
}
ExcelWriteKit.java
package com.trendy.fw.common.excel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.trendy.fw.common.config.Constants;
import com.trendy.fw.common.util.StringKit;
public class ExcelWriteKit {
protected static Logger log = LoggerFactory.getLogger(ExcelWriteKit.class);
private short fontSize = 11;
private CellStyle cellStyleCommon = null;
private CellStyle cellStyleHeader = null;
private CellStyle cellStyleNumeric = null;
private CellStyle cellStyleDate = null;
private Font fontStyleCommon = null;
private Font fontStyleBolder = null;
private boolean isNeedStyle = true;
public ExcelWriteKit() {
}
public Workbook createWorkbook(String fileType) {
Workbook wb = null;
if (fileType.equals(ExcelConfig.FT_XLS)) {
wb = new HSSFWorkbook();
} else {
wb = new SXSSFWorkbook(-1);
}
return wb;
}
/**
* 創建一個內容格,字符串格式
*
* @param wb
* 工作表
* @param row
* 行
* @param cellIndex
* 列
* @param cellValue
* 內容值
* @return
*/
public Cell createCell(Workbook wb, Row row, int cellIndex, String cellValue) {
Cell cell = row.createCell(cellIndex);
cell.setCellType(ExcelConfig.CT_STRING);
cell.setCellValue(cellValue);
cell.setCellStyle(getCommonCellStyle(wb));
return cell;
}
private CellStyle getCommonCellStyle(Workbook wb) {
if (isNeedStyle) {
if (cellStyleCommon == null) {
CellStyle cellStyle = wb.createCellStyle();
cellStyle = addCellBorder(cellStyle);
cellStyle.setFont(getCellFont(wb));
cellStyleCommon = cellStyle;
}
}
return cellStyleCommon;
}
/**
* 創建一個表頭內容格
*
* @param wb
* 工作表
* @param row
* 列
* @param cellIndex
* 行
* @param cellValue
* 內容值
* @return
*/
public Cell createHeaderCell(Workbook wb, Row row, int cellIndex, String cellValue) {
Cell cell = row.createCell(cellIndex);
cell.setCellValue(cellValue);
cell.setCellStyle(getHeaderCellStyle(wb));
return cell;
}
private CellStyle getHeaderCellStyle(Workbook wb) {
if (isNeedStyle) {
if (cellStyleHeader == null) {
CellStyle cellStyle = wb.createCellStyle();
cellStyle = addCellBorder(cellStyle);
cellStyle.setFont(getCellBoldFont(wb));
cellStyleHeader = cellStyle;
}
}
return cellStyleHeader;
}
/**
* 創建一個數字內容格
*
* @param wb
* 內容表
* @param row
* 列
* @param cellIndex
* 行
* @param cellValue
* 內容值
* @param formatStr
* 格式
* @return
*/
public Cell createNumericCell(Workbook wb, Row row, int cellIndex, double cellValue, String formatStr) {
Cell cell = row.createCell(cellIndex, ExcelConfig.CT_NUMERIC);
cell.setCellValue(cellValue);
cell.setCellStyle(getNumericCellStyle(wb, formatStr));
return cell;
}
private CellStyle getNumericCellStyle(Workbook wb, String formatStr) {
if (isNeedStyle) {
if (cellStyleNumeric == null) {
CellStyle cellStyle = wb.createCellStyle();
cellStyle = addCellBorder(cellStyle);
cellStyle.setFont(getCellFont(wb));
DataFormat format = wb.createDataFormat();
cellStyle.setDataFormat(format.getFormat(formatStr));
cellStyle.setAlignment(CellStyle.ALIGN_RIGHT);
cellStyleNumeric = cellStyle;
}
}
return cellStyleNumeric;
}
/**
* 創建一個日期內容格
*
* @param wb
* 內容表
* @param row
* 列
* @param cellIndex
* 行
* @param cellValue
* 內容值
* @param formatStr
* 格式
* @return
*/
public Cell createDateCell(Workbook wb, Row row, int cellIndex, Date cellValue, String formatStr) {
Cell cell = row.createCell(cellIndex);
cell.setCellValue(cellValue);
cell.setCellStyle(getDateCellStyle(wb, formatStr));
return cell;
}
private CellStyle getDateCellStyle(Workbook wb, String formatStr) {
if (isNeedStyle) {
if (cellStyleDate == null) {
CellStyle cellStyle = wb.createCellStyle();
cellStyle = addCellBorder(cellStyle);
cellStyle.setFont(getCellFont(wb));
cellStyleDate = cellStyle;
}
}
return cellStyleDate;
}
/**
* 增加內容格邊線
*
* @param cellStyle
* @return
*/
public CellStyle addCellBorder(CellStyle cellStyle) {
cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
cellStyle.setBorderRight(CellStyle.BORDER_THIN);
cellStyle.setBorderTop(CellStyle.BORDER_THIN);
return cellStyle;
}
/**
* 獲取普通字體
*
* @param wb
* 工作表
* @return
*/
public Font getCellFont(Workbook wb) {
if (fontStyleCommon == null) {
Font font = wb.createFont();
font.setFontHeightInPoints(getFontSize());
fontStyleCommon = font;
}
return fontStyleCommon;
}
/**
* 獲取加粗字體
*
* @param wb
* 工作表
* @return
*/
public Font getCellBoldFont(Workbook wb) {
if (fontStyleBolder == null) {
Font font = wb.createFont();
font.setFontHeightInPoints(getFontSize());
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
fontStyleBolder = font;
}
return fontStyleBolder;
}
/**
* 寫Excel工作簿
*
* @param bean
* WriteExcelBean
* @return Workbook工作簿對象
*/
public Workbook writeExcel(ExcelWriteBean bean) {
Workbook wb = createWorkbook(bean.getFileType());
String sheetName = bean.getSheetName();
if (!StringKit.isValid(sheetName)) {
sheetName = "sheet1";
}
Sheet sheet = wb.createSheet(sheetName);
// 處理表頭內容
if (bean.getHeaderList().size() > 0) {
Row row = sheet.createRow(0);
for (int i = 0; i < bean.getHeaderList().size(); i++) {
String headerValue = bean.getHeaderList().get(i);
createHeaderCell(wb, row, i, headerValue);
}
}
// 處理表中內容
if (bean.getContentList().size() > 0) {
int rowCount = 1;// 行計數器
// 沒有表頭的情況
if (bean.getHeaderList().size() == 0) {
rowCount = 0;
}
for (List<Object> contentList : bean.getContentList()) {
Row row = sheet.createRow(rowCount);
for (int i = 0; i < contentList.size(); i++) {
Object cellValue = contentList.get(i);
if (getCellType(i, bean.getCellTypeMap()) == ExcelConfig.CT_NUMERIC) {
if (cellValue == null) {// 如果值為空,默認填0
cellValue = new Integer(0);
}
createNumericCell(wb, row, i, Double.valueOf(cellValue.toString()),
getCellFormat(i, bean.getCellFormatMap()));
} else {
if (cellValue == null) {// 如果值為空,默認空字符串
cellValue = new String("");
}
createCell(wb, row, i, cellValue.toString());
}
}
rowCount++;
if (rowCount % 100 == 0) {
try {
((SXSSFSheet) sheet).flushRows(100);
} catch (Exception e) {
log.error("", e);
}
}
}
}
return wb;
}
/**
* 寫Excel工作簿多個sheet
*
* @param bean
* WriteExcelBean
* @return Workbook工作簿對象
*/
public Workbook writeExcel(List<ExcelWriteBean> excelWriteList) {
if(excelWriteList == null || excelWriteList.size()==0){
return null;
}
Workbook wb = createWorkbook(excelWriteList.get(0).getFileType());
int sheetNumber = 0;
for(ExcelWriteBean bean : excelWriteList){
sheetNumber++;
String sheetName = bean.getSheetName();
if (!StringKit.isValid(sheetName)) {
sheetName = "sheet"+sheetNumber;
}
Sheet sheet = wb.createSheet(sheetName);
// 處理表頭內容
if (bean.getHeaderList().size() > 0) {
Row row = sheet.createRow(0);
for (int i = 0; i < bean.getHeaderList().size(); i++) {
String headerValue = bean.getHeaderList().get(i);
createHeaderCell(wb, row, i, headerValue);
}
}
// 處理表中內容
if (bean.getContentList().size() > 0) {
int rowCount = 1;// 行計數器
// 沒有表頭的情況
if (bean.getHeaderList().size() == 0) {
rowCount = 0;
}
for (List<Object> contentList : bean.getContentList()) {
Row row = sheet.createRow(rowCount);
for (int i = 0; i < contentList.size(); i++) {
Object cellValue = contentList.get(i);
if (getCellType(i, bean.getCellTypeMap()) == ExcelConfig.CT_NUMERIC) {
if (cellValue == null) {// 如果值為空,默認填0
cellValue = new Integer(0);
}
createNumericCell(wb, row, i, Double.valueOf(cellValue.toString()),
getCellFormat(i, bean.getCellFormatMap()));
} else {
if (cellValue == null) {// 如果值為空,默認空字符串
cellValue = new String("");
}
createCell(wb, row, i, cellValue.toString());
}
}
rowCount++;
if (rowCount % 100 == 0) {
try {
((SXSSFSheet) sheet).flushRows(100);
} catch (Exception e) {
log.error("", e);
}
}
}
}
}
return wb;
}
/**
* 輸出Excel文件
*
* @param bean
* WriteExcelBean
* @param filePath
* 文件全路徑
*/
public void outputExcel(ExcelWriteBean bean, String filePath) {
FileOutputStream fos = null;
try {
Workbook wb = writeExcel(bean);
String fileName = bean.getFileName() + "." + bean.getFileType();
fos = new FileOutputStream(filePath + Constants.FILE_SEPARATOR + fileName);
wb.write(fos);
fos.close();
} catch (IOException e) {
log.error("輸出文件[{}]出錯:", filePath, e);
} catch (Exception e) {
log.error("輸出文件[{}]出錯:", filePath, e);
} finally {
try {
if (fos != null)
fos.close();
} catch (Exception e) {
log.error("輸出文件[{}]出錯:", filePath, e);
}
}
}
/**
* 獲取cell的類型
*
* @param cellIndex
* @param cellTypeMap
* @return
*/
private int getCellType(int cellIndex, HashMap<Integer, Integer> cellTypeMap) {
int cellType = ExcelConfig.CT_STRING;
try {
if (!cellTypeMap.isEmpty()) {
cellType = cellTypeMap.get(cellIndex);
}
} catch (Exception e) {
cellType = ExcelConfig.CT_STRING;
}
return cellType;
}
/**
* 獲取cell的格式
*
* @param cellIndex
* @param cellFormatMap
* @return
*/
private String getCellFormat(int cellIndex, HashMap<Integer, String> cellFormatMap) {
String cellFormat = "";
try {
if (!cellFormatMap.isEmpty()) {
cellFormat = cellFormatMap.get(cellIndex);
}
} catch (Exception e) {
cellFormat = "";
}
return cellFormat;
}
public short getFontSize() {
return fontSize;
}
public void setFontSize(short fontSize) {
this.fontSize = fontSize;
}
public CellStyle getCellStyleCommon() {
return cellStyleCommon;
}
public void setCellStyleCommon(CellStyle cellStyleCommon) {
this.cellStyleCommon = cellStyleCommon;
}
public CellStyle getCellStyleHeader() {
return cellStyleHeader;
}
public void setCellStyleHeader(CellStyle cellStyleHeader) {
this.cellStyleHeader = cellStyleHeader;
}
public CellStyle getCellStyleNumeric() {
return cellStyleNumeric;
}
public void setCellStyleNumeric(CellStyle cellStyleNumeric) {
this.cellStyleNumeric = cellStyleNumeric;
}
public CellStyle getCellStyleDate() {
return cellStyleDate;
}
public void setCellStyleDate(CellStyle cellStyleDate) {
this.cellStyleDate = cellStyleDate;
}
public Font getFontStyleCommon() {
return fontStyleCommon;
}
public void setFontStyleCommon(Font fontStyleCommon) {
this.fontStyleCommon = fontStyleCommon;
}
public Font getFontStyleBolder() {
return fontStyleBolder;
}
public void setFontStyleBolder(Font fontStyleBolder) {
this.fontStyleBolder = fontStyleBolder;
}
public boolean getIsNeedStyle() {
return isNeedStyle;
}
public void setIsNeedStyle(boolean isNeedStyle) {
this.isNeedStyle = isNeedStyle;
}
}
WebExcelWriteKit.java
package com.trendy.fw.common.excel;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import com.trendy.fw.common.web.HttpResponseKit;
public class WebExcelWriteKit extends ExcelWriteKit {
/**
* 輸出成文檔
*
* @param wb
* 工作表
* @param fileName
* 文件名
* @param response
*/
public void output(Workbook wb, String fileName, HttpServletRequest request, HttpServletResponse response) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
wb.write(os);
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
response.reset();
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
HttpResponseKit.setAttachmentFile(request, response, fileName);
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
// Simple read/write loop.
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (IOException e) {
log.error("輸出Excel出錯:", e);
} catch (Exception e) {
log.error("輸出Excel出錯:", e);
} finally {
try {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
if (os != null)
os.close();
} catch (Exception e) {
log.error("輸出Excel出錯:{}", e);
}
}
}
/**
* 從頁面上輸出Excel
*
* @param bean
* WriteExcelBean
* @param response
*/
public void outputExcel(ExcelWriteBean bean, HttpServletRequest request, HttpServletResponse response) {
Workbook wb = writeExcel(bean);
String fileName = bean.getFileName() + "." + bean.getFileType();
output(wb, fileName, request, response);
}
/**
* 從頁面上輸出Excel多個sheet
*
* @param bean
* WriteExcelBean
* @param response
*/
public void outputExcel(List<ExcelWriteBean> excelWriteList, HttpServletRequest request, HttpServletResponse response) {
Workbook wb = writeExcel(excelWriteList);
String fileName = excelWriteList.get(0).getFileName() + "." + excelWriteList.get(0).getFileType();
output(wb, fileName, request, response);
}
}
使用說明
將以上代碼放到同一個excel包中,在對Excel進行讀寫的操作的時候,分別調用ExcelReadKit和ExcelWriteKit兩個類中的方法,可以很方便地將Excel中的內容轉換成ExcelReadResultBean對象,封裝ExcelWriteBean對象將數據寫入Excel文件中。
備注:以上代碼使用需要依賴 apache poi jar包,記得先引入到項目當中
源碼共享在https://github.com/xiongyouqiang/trendy_framework.git 大家有需要的話可以下載看看。
智能推薦
freemarker + ItextRender 根據模板生成PDF文件
1. 制作模板 2. 獲取模板,并將所獲取的數據加載生成html文件 2. 生成PDF文件 其中由兩個地方需要注意,都是關于獲取文件路徑的問題,由于項目部署的時候是打包成jar包形式,所以在開發過程中時直接安照傳統的獲取方法沒有一點文件,但是當打包后部署,總是出錯。于是參考網上文章,先將文件讀出來到項目的臨時目錄下,然后再按正常方式加載該臨時文件; 還有一個問題至今沒有解決,就是關于生成PDF文件...
電腦空間不夠了?教你一個小秒招快速清理 Docker 占用的磁盤空間!
Docker 很占用空間,每當我們運行容器、拉取鏡像、部署應用、構建自己的鏡像時,我們的磁盤空間會被大量占用。 如果你也被這個問題所困擾,咱們就一起看一下 Docker 是如何使用磁盤空間的,以及如何回收。 docker 占用的空間可以通過下面的命令查看: TYPE 列出了docker 使用磁盤的 4 種類型: Images:所有鏡像占用的空間,包括拉取下來的鏡像,和本地構建的。 Con...
requests實現全自動PPT模板
http://www.1ppt.com/moban/ 可以免費的下載PPT模板,當然如果要人工一個個下,還是挺麻煩的,我們可以利用requests輕松下載 訪問這個主頁,我們可以看到下面的樣式 點每一個PPT模板的圖片,我們可以進入到詳細的信息頁面,翻到下面,我們可以看到對應的下載地址 點擊這個下載的按鈕,我們便可以下載對應的PPT壓縮包 那我們就開始做吧 首先,查看網頁的源代碼,我們可以看到每一...
猜你喜歡
Linux C系統編程-線程互斥鎖(四)
互斥鎖 互斥鎖也是屬于線程之間處理同步互斥方式,有上鎖/解鎖兩種狀態。 互斥鎖函數接口 1)初始化互斥鎖 pthread_mutex_init() man 3 pthread_mutex_init (找不到的情況下首先 sudo apt-get install glibc-doc sudo apt-get install manpages-posix-dev) 動態初始化 int pthread_...
統計學習方法 - 樸素貝葉斯
引入問題:一機器在良好狀態生產合格產品幾率是 90%,在故障狀態生產合格產品幾率是 30%,機器良好的概率是 75%。若一日第一件產品是合格品,那么此日機器良好的概率是多少。 貝葉斯模型 生成模型與判別模型 判別模型,即要判斷這個東西到底是哪一類,也就是要求y,那就用給定的x去預測。 生成模型,是要生成一個模型,那就是誰根據什么生成了模型,誰就是類別y,根據的內容就是x 以上述例子,判斷一個生產出...
styled-components —— React 中的 CSS 最佳實踐
https://zhuanlan.zhihu.com/p/29344146 Styled-components 是目前 React 樣式方案中最受關注的一種,它既具備了 css-in-js 的模塊化與參數化優點,又完全使用CSS的書寫習慣,不會引起額外的學習成本。本文是 styled-components 作者之一 Max Stoiber 所寫,首先總結了前端組件化樣式中的最佳實踐原則,然后在此基...
19.vue中封裝echarts組件
19.vue中封裝echarts組件 1.效果圖 2.echarts組件 3.使用組件 按照組件格式整理好數據格式 傳入組件 home.vue 4.接口返回數據格式...