Java使用Poi進行excel的文件導出,下載
先貼代碼後講解
導出方法1(確認已經有可導出的模板)
例如:
No: | ${no} | |
確認日期: | ${date} | |
確認人: | ${p} |
import org.apache.poi.ss.usermodel.Workbook;
/**
*
* @param sheetList
* 傳入sheetList(sheet名稱)
* @param dataList
* 傳入導入數據List
* @param in 文件輸入流
* @return Workbook 返回創建好的文件,在上層直接用此寫入OutputStream 導出文件即可
* @throws InvalidFormatException
* @throws ParsePropertyException
*/
public static Workbook exportCertificate( @NotNull ArrayList<String> sheetList,@NotNull CertificateVo certificateVo,@NotNull InputStream in) throws ParsePropertyException, InvalidFormatException {
// 判斷數值是否爲正常數值,否則返回
if (templateFileType < 0 && templateFileType > 8 && sheetList.size() < 0
&& certificateVo!=null &&in!= null) {
return null;
}
HashMap<String, String> intoExcelMap = new HashMap<String, String>();
// 所有excel都有的三個參數 No,時間,人名 ,
intoExcelMap.put("no", certificateVo.getNo());
intoExcelMap.put("date", certificateVo.getDate());
intoExcelMap.put("p", certificateVo.getPersonName());
//讀取傳入in中的模版並創建一個副本
XLSTransformer transformer = new XLSTransformer();
return transformer.transformXLS(in, intoExcelMap);
}
以上代碼爲抽象出去的工具類,代碼中都有對應的註釋。
這裏把參數傳入excel 中有2個步驟
1 .需要在excel 中輸入${key};
2. 使用poi 的中的XLSTransformer.transformXLS(InputStream is, Map beanParams)方法,此方法第一個參數是傳入讀取的模板輸入流,第二個爲hashMap,hashMap的key 爲你在excel 表格中輸入的key值,value 爲你要傳入參數的值。
transformer還有其他的方法,例如transformMultipleSheetsList轉換多列表格
transformer.transformMultipleSheetsList(in, dataList, sheetList, "List", new HashMap(),0);
以下爲2個方法的註釋,大家可自行做相對應的理解
/**
* Creates Workbook instance based on .xls template from a given InputStream and a number of beans
*
* @param is xls InputStream with required
* @param beanParams Beans in a map under keys used in .xls template to access to the beans
* @return new {@link org.apache.poi.ss.usermodel.Workbook} generated by inserting beans into corresponding excel template
* @throws net.sf.jxls.exception.ParsePropertyException if there were any problems in evaluating specified property value from a bean
*/
transformXLS(InputStream is, Map beanParams)
/**
* This method transforms given XLS input stream template into multiple sheets workbook
* creating separate Excel worksheet for every object in the list
* @param is - {@link InputStream} for source XLS template file
* @param objects - List of beans where each list item should be exported into a separated worksheet
* @param newSheetNames - Sheet names to be used for newly created worksheets
* @param beanName - Bean name to be used for a list item when processing sheet
* @param beanParams - Common bean map containing all other objects to be used in the workbook
* @param startSheetNum - Worksheet number (zero based) of the worksheet that needs to be used to create multiple worksheets
* @return new {@link org.apache.poi.ss.usermodel.Workbook} object containing the result of transformation
* @throws net.sf.jxls.exception.ParsePropertyException - {@link ParsePropertyException} is thrown when some property can't be parsed
*/
transformMultipleSheetsList(InputStream is, List objects, List newSheetNames, String beanName, Map beanParams, int startSheetNum)
作爲輸出流傳出下載
@RequestMapping(value = "exportCertificate")
public void export(HttpServletRequest request, HttpServletResponse response) {
// 測試使用
String templateFileName = request.getSession().getServletContext().getRealPath("/")
+ "/static/xls/test.xls";
// 測試證書名稱
String cName = "test";
// sheet問卷名稱
ArrayList<String> sheetList = new ArrayList<String>();
sheetList.add(cName);
// 導出文件文件名稱 yyyy-MM-dd hh:mm:ss不使用:原因,windows 文件不能用:命名
String exportFileName = cName + new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()) + ".xls";
CertificateVo certificateVo = new CertificateVo();
certificateVo.setNo("45123456789375");
certificateVo.setPersonName("test");
certificateVo.setDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
// 導出輸出流
OutputStream out = null;
// 讀取輸入流
InputStream in = null;
// 定義流
try {
// 讀取輸入流
in = new BufferedInputStream(new FileInputStream(templateFileName));
out = response.getOutputStream();
Workbook worktab = ZtpUtil.exportCertificate( sheetList, certificateVo, in);
// 設置響應
// 服務端要求客戶端以下載文件的方式打開該文件
// 設置文件可以爲中文名稱
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(exportFileName.getBytes("utf-8"), "ISO-8859-1"));
// 設置數據類型
response.setContentType("application/vnd.ms-excel");
worktab.write(out);
} catch (ParsePropertyException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.flush();
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
這是在服務端使用的部分代碼,如果錯誤異常,自己需要做相對應的處理。
導出方法2
自己生成excel
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("table");// 創建table工作薄
short colorIndex = 10;
HSSFPalette palette = wb.getCustomPalette();// 自定義顏色
Color rgb = Color.RED;
short bgIndex = colorIndex++; // 背景顏色下標值
palette.setColorAtIndex(bgIndex, (byte) rgb.getRed(), (byte) rgb.getGreen(), (byte) rgb.getBlue());
short bdIndex = colorIndex++; // 邊框顏色下標值
palette.setColorAtIndex(bdIndex, (byte) rgb.getRed(), (byte) rgb.getGreen(), (byte) rgb.getBlue());
short fontColorIndex = colorIndex++; // 文字的顏色
rgb = Color.WHITE;
palette.setColorAtIndex(fontColorIndex, (byte) rgb.getRed(), (byte) rgb.getGreen(), (byte) rgb.getBlue());
List<ArrayList<String>> parentlist = new ArrayList<ArrayList<String>>();
ArrayList<String> childList = new ArrayList<String>();
childList.add("證明");
ArrayList<String> childList2 = new ArrayList<String>();
childList2.add("No:");
childList2.add("12313234213");
ArrayList<String> childList3 = new ArrayList<String>();
childList3.add("日期:");
SimpleDateFormat f = new SimpleDateFormat("yyyy 年 MM 月 dd 日");
childList3.add(f.format(new Date()));
ArrayList<String> childList4 = new ArrayList<String>();
childList4.add("人員:");
childList4.add("test");
parentlist.add(childList);
parentlist.add(childList2);
parentlist.add(childList3);
parentlist.add(childList4);
// 創建表格行列
HSSFRow row;
HSSFCell cell;
for (int i = 0; i < parentlist.size(); i++) {
row = sheet.createRow(i);// 創建表格行
for (int j = 0; j < parentlist.get(i).size(); j++) {
cell = row.createCell(j);// 根據表格行創建單元格
cell.setCellValue(parentlist.get(i).get(j));
/**
* create a new Font and add it to the workbook's font table
* 創建新字體並將其添加到工作簿的字體表中
*/
HSSFFont font = wb.createFont();
// xls 高級設置
HSSFCellStyle cellStyle = wb.createCellStyle();
if (i == 0) {// 設置背景色
cellStyle.setFillForegroundColor(bgIndex);
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
//
/**
* 設置單元格的水平對齊類型 * set the type of horizontal alignment for
* the cell
*
* @param align
* - the type of alignment
* @see #ALIGN_GENERAL
* @see #ALIGN_LEFT
* @see #ALIGN_CENTER
* @see #ALIGN_RIGHT
* @see #ALIGN_FILL
* @see #ALIGN_JUSTIFY
* @see #ALIGN_CENTER_SELECTION
*/
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
font.setColor(fontColorIndex);// 設置文字的顏色
// int firstRow, int lastRow, int firstCol, int lastCol
CellRangeAddress region = new CellRangeAddress(0, 0, 0, 2);
// 設置合併單元格
sheet.addMergedRegion(region);
} else {
cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
font.setColor(bgIndex);// 設置文字的顏色
// int firstRow, int lastRow, int firstCol, int lastCol
CellRangeAddress region = new CellRangeAddress(i, i, 1, 2);
// 設置合併單元格
sheet.addMergedRegion(region);
}
/**
* 設置單元格的垂直對齊類型
*
* @param align
* the type of alignment
* @see #VERTICAL_TOP
* @see #VERTICAL_CENTER
* @see #VERTICAL_BOTTOM
* @see #VERTICAL_JUSTIFY
*/
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cell.setCellStyle(cellStyle);
// 設置文字
cellStyle.setFont(font);
}