這篇文章將為大家詳細講解有關Java中poi如何導出Excel下載到客戶端,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
具體內容如下
Maven配置,包含了其他文件格式的依賴,就全貼出來了
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-excelant</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.8</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.8</version> </dependency>
Service層
@Override
public void export(Long sblsh, String excelName, OutputStream out) {
try {
// 第一步,創建一個webbook,對應一個Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//生成一個表格
HSSFSheet sheet = wb.createSheet(excelName);
// 第三步,在sheet中添加表頭第0行
HSSFRow row = sheet.createRow(0);
// 第四步,創建單元格,并設置值表頭 設置表頭居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式
HSSFCell cell = row.createCell(0);
cell.setCellStyle(style);
Byte kjzz = qyjbxxMapper.getKjzz(sblsh);
List<A> record = this.selectBySblsh(sblsh);
this.insertData(wb, sheet, row, record, out);
}
} catch (Exception e) {
logger.info(e.getMessage());
}
}
/**
* 導入數據到表格中
* @param wb execl文件
* @param sheet 表格
* @param row 表格行
* @param record 要導出的數據
* @param out 輸出流
*/
private void insertData(HSSFWorkbook wb,HSSFSheet sheet,HSSFRow row,List<A> record,
OutputStream out){
try {
row = sheet.createRow(1);
for(int i=0;i<title.length;i++){
row.createCell(i).setCellValue(title[i]);
}
for(int i=0;i<record.size();i++){
row = sheet.createRow(i+2);
A data = record.get(i);
row.createCell(0).setCellValue(data.getHc());
row.createCell(1).setCellValue(data.getXm());
BigDecimal je = data.getJe();
if(je!=null){
row.createCell(2).setCellValue(je.doubleValue());
}
}
//合并單元格,前面2位代表開頭結尾行,后面2位代表開頭結尾列
CellRangeAddress region = new CellRangeAddress(0,0,0,title.length-1);
sheet.addMergedRegion(region);
wb.write(out);
out.flush();
out.close();
wb.close();
} catch (Exception e) {
logger.info(e.getMessage());
}
}Controller
@RequestMapping("/export")
public void export(Long sblsh, HttpServletRequest request, HttpServletResponse response){
response.setContentType("octets/stream");
String excelName = "文件名";
try {
response.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");
OutputStream out = response.getOutputStream();
aService.export(sblsh,excelName ,out);
} catch (Exception e) {
e.printStackTrace();
}
}關于“Java中poi如何導出Excel下載到客戶端”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。