java后台处理excel_java后台利用Apache poi 生成excel文档提供前台下载示例
之前在項(xiàng)目中會(huì)用到在java在后臺(tái)把數(shù)據(jù)填入Word文檔的模板來(lái)提供前臺(tái)下載,為了自己能隨時(shí)查看當(dāng)時(shí)的實(shí)現(xiàn)方案及方便他人學(xué)習(xí)我寫了這篇博客,訪問(wèn)量已經(jīng)是我寫的博客里第一了。于是乎我在學(xué)會(huì)用Java在后臺(tái)利用Apache poi 生成excel文檔提供前臺(tái)下載之后就想著來(lái)寫一篇姊妹篇啦。
在生成Excel文檔的時(shí)候我采用了和生成Word時(shí)的不同方法,Apache poi。它是用Java編寫的免費(fèi)開(kāi)源的跨平臺(tái)的 Java API,提供API給Java程式對(duì)Microsoft Office格式檔案讀和寫的功能。想要實(shí)現(xiàn)這個(gè)功能,就按照下面的步驟來(lái)做吧,為了方便起見(jiàn),我直接拿項(xiàng)目中遇到的實(shí)例來(lái)舉例說(shuō)明,是的,我在寫這篇博客的時(shí)候同時(shí)也在完成手上的項(xiàng)目。
step1:創(chuàng)建xls格式的模板
表頭含有我的甲方信息就打碼了,可以看到我搞了一個(gè)空的模板文件,現(xiàn)在有很多東西需要在后臺(tái)填入
step2:前臺(tái)觸發(fā)事件
搞一個(gè)按鈕,用戶點(diǎn)擊的時(shí)候用javascript的window.location.href將頁(yè)面重定向到你處理下載的URL去
比方說(shuō),這是我項(xiàng)目的前臺(tái),看到那個(gè)表面質(zhì)量按鈕嗎,來(lái)看一下當(dāng)它被點(diǎn)擊的時(shí)候調(diào)用的函數(shù)
function exportBatch() {
//get請(qǐng)求,可以傳遞參數(shù),比方說(shuō)我這里就傳了一堆卷號(hào),我只生成傳過(guò)去的這堆卷號(hào)的檢驗(yàn)記錄
//參數(shù)rollNumbers的細(xì)節(jié)就不展示了,業(yè)務(wù)相關(guān)
window.location.href = '../ir/exportSurface?rollNumberList=' + rollNumbers;
}
有朋友可能想用什么Ajax來(lái)發(fā)送請(qǐng)求,我反正是沒(méi)搞出來(lái),挺麻煩的,網(wǎng)上找的相關(guān)解決方案也都比較蛋疼,因此不傳什么復(fù)雜的敏感的參數(shù),就這么寫就可以。
step3:后臺(tái)處理
首先你當(dāng)然要把Apache poi那一套東西引入你的項(xiàng)目啦,我的項(xiàng)目是Maven項(xiàng)目,添加依賴很容易
org.apache.poi
poi
3.14
然后,為了方便導(dǎo)出Excel,在項(xiàng)目中建了一個(gè)ExcelUtils工具類,后面給出源碼,這么一來(lái)導(dǎo)出Excel會(huì)變得更簡(jiǎn)單。ExcelUtils里面rXogrNBYP除了一些既定的方法外,還有就是你具體怎么去操作模板的方法了。當(dāng)然你用的少的話可以不用我這工具類,而是在你需要的時(shí)候import相關(guān)的類,然后在你處理的時(shí)候就把操作模板的邏輯寫進(jìn)去也可以。但我這個(gè)項(xiàng)目很多次用到導(dǎo)出Excel,所以抽象出一個(gè)工具類是很有必要的,符合設(shè)計(jì)模式。
我的項(xiàng)目是基于SpringMVC的,來(lái)看看我后臺(tái)接收到請(qǐng)求以后做了些什么吧
Controller:
/***
* 批量導(dǎo)出表面質(zhì)量檢驗(yàn)記錄
*
* @return
* @throws Exception
*/
@RequestMapping(value = "exportSurface", method = RequestMethod.GET)
@ResponseBody
public void exportSurface(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//參數(shù)獲取及處理,業(yè)務(wù)相關(guān)不展示
//把要填寫的數(shù)據(jù)放在一個(gè)map里
Map map = new HashMap();
map.put("sequence", "0001");//mock編號(hào)
map.put("date", DateUtils.toDateStr(new Date(), DateUtils.DEFAULT_DATE_PATTERN_CHINES
最后調(diào)用ExcelUtils里的相關(guān)導(dǎo)出方法,這個(gè)方法是自定義的,它定義的是怎樣去操作模板
自定義的方法:
public static void exportInspectionRecordSurface(HttpServletRequest request, HttpServletResponse response, Map map) throws IOException {
//模板的路徑,這個(gè)在自己的項(xiàng)目中很容易弄錯(cuò),相對(duì)位置一定要寫對(duì)啊
String prXogrNBYPsth = request.getRealPath("/") + INSPECTIONRECORD_SURFACE_TEMPLET_PATH;
Workbook webBook = readExcel(psth);
createCellStyle(webBook);
Sheet sheet = webBook.getSheetAt(0);
//開(kāi)始操作模板,找到某行某列(某個(gè)cell),需要注意的是這里有個(gè)坑,行和列的計(jì)數(shù)都是從0開(kāi)始的
//一次數(shù)據(jù)插入的位置不對(duì),別灰心,多試幾次就好啦,你要是能看懂我下面的代碼,數(shù)據(jù)插在了什么位置,你就明白了
int rows = 1;
Row row = sheet.getRow(rows);
row.createCell(1).setCellValue((String) map.get("sequence"));
row.createCell(3).setCellValue((String) map.get("date"));
row.createCell(9).setCellValue((String) map.get("chetaihao"));
rows = 2;
row = sheet.getRow(rows);
row.createCell(1).setCellValue((String) map.get("productName"));
row.createCell(3).setCellValue((String) map.get("specification"));
row.createCell(9).setCellValue((String) map.get("memo"));
//檢驗(yàn)記錄的插入業(yè)務(wù)相關(guān),不展示,其實(shí)就是for循環(huán)在合適的行合適的列插入一個(gè)個(gè)對(duì)象的屬性即可,你這么聰明,沒(méi)問(wèn)題的
writeExcel(response, webBook, "表面質(zhì)量檢驗(yàn)記錄");
}
ExcelUtils:
//這里得有你自己的package名
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.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by bwju on 2016/12/06.
*/
public class ExcelUtils {
private static final String INSPECTIONRECORD_SURFACE_TEMPLET_PATH = "/asserts/templete/InspectionRecordSurface.xls";
private static HSSFCellStyle cellstyle = null;
public static void exportInspectionRecordSurface(HttpServletRequest request, HttpServletResponse response, Map map) throws IOException {
//實(shí)現(xiàn)上文里有,改個(gè)函數(shù)名,寫你的操作模板函數(shù)吧!
}
private static Workbook readExcel(String filePath) {
InputStream in = null;
Workbook work = null;
try {
in = new FileInputStream(filePath);
work = new HSSFWorkbook(in);
} catch (FileNotFoundException e) {
System.out.println("文件路徑錯(cuò)誤");
e.printStackTrace();
} catch (IOException e) {
System.out.println("文件輸入流錯(cuò)誤");
e.printStackTrace();
}
return work;
}rXogrNBYP
private static void writeExcel(HttpServletResponse response, Workbook work, String fileName) throws IOException {
OutputStream out = null;
try {
out = response.getOutputStream();
response.setContentType("application/ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName + ".xls", "UTF-8"))));
work.write(out);
} catch (IOException e) {
System.out.println("輸出流錯(cuò)誤");
e.printStackTrace();
} finally {
out.close();
}
}
private static Cell setCellStyleWithStyleAndValue(CellStyle style, Cell cell, String value) {
cell.setCellStyle(style);
cell.setCellValue(value);
return cell;
}
private static Cell setCellStyleWithValue(Cell cell, String value) {
cell.setCellStyle(cellstyle);
cell.setCellValue(value);
return cell;
}
private static Cell setCellStyleWithStyleAndValue(CellStyle style, Cell cell, RichTextString value) {
cell.setCellStyle(style);
cell.setCellValue(value);
return cell;
}
private static Cell setCellStyleWithValue(Cell cell, int value) {
cell.setCellStyle(cellstyle);
cell.setCellValue(value);
return cell;
}
private static Cell setCellStyleWithValue(Cell cell, double value) {
cell.setCellStyle(cellstyle);
cell.setCellValue(value);
return cell;
}
private static HSSFCellStyle createCellStyle(Workbook wb) {
cellstyle = (HSSFCellStyle) wb.createCellStyle();
cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENwww.cppcns.comTER);
cellstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return cellstyle;
}
}
step4:啟動(dòng)項(xiàng)目,然后測(cè)試一下,看!完美的導(dǎo)出了。。。有圖為證
嗯嗯,文章寫到這里就結(jié)束啦,Apache poi還提供了很多API在本例中為得到展示,比如能夠指定樣式等等。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
本文標(biāo)題: java后臺(tái)利用Apache poi 生成excel文檔提供前臺(tái)下載示例
本文地址: http://www.cppcns.com/ruanjian/java/190786.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的java后台处理excel_java后台利用Apache poi 生成excel文档提供前台下载示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 怎么在Windows 11中为音频输出选
- 下一篇: html能插入背景的行级元素,Html元