Excel下載?
依賴
<!-- excel文件處理 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
Controller
@RequestMapping("/down")
public void exportExcel(HttpServletRequest request, HttpServletResponse response)throws Exception {
OutputStream output = response.getOutputStream();
response.reset();
response.setCharacterEncoding("UTF-8");
String fileNeme ="下載" + System.currentTimeMillis() +".xlsx";
//設置下載的excel 文件名支持中文
? ? fileNeme = URLEncoder.encode(fileNeme,"UTF-8");
response.setHeader("Content-disposition","attachment;filename=" + fileNeme);
response.setContentType("application/vnd.ms-excel;charset=utf-8");
String[] titles = {"測試表頭","測試表頭2"};
List> list =new ArrayList<>();
Map map =new HashMap<>();
map.put("0","測試");
map.put("1","測2");
list.add(map);
ExcelUtil.export2007ExcelByPOI("sheet", titles, list, output);
}
工具類
package com.start.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtil {
/** EXCEL 2003 */
? ? private static final StringEXCEL_XLS ="xls";
/** EXCEL 2007/2010 */
? ? private static final StringEXCEL_XLSX ="xlsx";
private ExcelUtil() {
}
/**
? ? * 從EXCEl中讀取數(shù)據(jù),結構為:單元格一行用一個map記錄,key:是單元格數(shù)字索引,從1開始,value:單元格的值
? ? *
? ? * @param file
? ? * @return
? ? * @throws Exception
*/
? ? public static List> readExcel(File file)throws Exception {
if (!file.exists()) {
return null;
}
List> dataList =new ArrayList>();
FileInputStream fis =new FileInputStream(file);
Workbook workBook =null;
if (file.getName().endsWith(EXCEL_XLS)) {// Excel 2003
? ? ? ? ? ? workBook =new HSSFWorkbook(fis);
}else if (file.getName().endsWith(EXCEL_XLSX)) {// Excel 2007/2010
? ? ? ? ? ? workBook =new XSSFWorkbook(fis);
}
int numberOfSheets = workBook.getNumberOfSheets();
for (int s =0; s < numberOfSheets; s++) {
Sheet sheetAt = workBook.getSheetAt(s);
// 獲取標題行
? ? ? ? ? ? Row titleRow = sheetAt.getRow(0);
// 獲取總列數(shù)
? ? ? ? ? ? int colCount = titleRow.getLastCellNum();
// 獲取當前Sheet的總列數(shù)
? ? ? ? ? ? int rowsCount = sheetAt.getPhysicalNumberOfRows();
for (int rowIndex =1; rowIndex < rowsCount; rowIndex++) {// 總行
? ? ? ? ? ? ? ? Row currentRow = sheetAt.getRow(rowIndex);
if (currentRow ==null) {
continue;
}
// 定義返回的數(shù)據(jù):key:列數(shù),從1 開始;object :列對應的值 一個Map,一行數(shù)據(jù)
? ? ? ? ? ? ? ? Map mapValue =new HashMap();
// 讀取每一列的信息
? ? ? ? ? ? ? ? for (int colIndex =0; colIndex < colCount; colIndex++) {
Cell cell = currentRow.getCell(colIndex);
if (cell ==null) {
continue;
}
String cellValue =null;
CellType cellType = cell.getCellType();
// 文本
? ? ? ? ? ? ? ? ? ? if (cellType == CellType.STRING) {
cellValue = cell.getStringCellValue();
}
// 數(shù)字
? ? ? ? ? ? ? ? ? ? else if (cellType == CellType.NUMERIC) {
// 先看是否是日期格式
? ? ? ? ? ? ? ? ? ? ? ? if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
// 讀取日期格式
? ? ? ? ? ? ? ? ? ? ? ? ? ? Date dateValue = cell.getDateCellValue();
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-mm-dd");
cellValue = sdf.format(dateValue);
}else {
// cell.setBlank();
? ? ? ? ? ? ? ? ? ? ? ? ? ? NumberFormat nf = NumberFormat.getInstance();
cellValue = nf.format(cell.getNumericCellValue());
if (cellValue.indexOf(",") >=0) {
cellValue = cellValue.replace(",","");
}
}
}
// 公式
? ? ? ? ? ? ? ? ? ? else if (cellType == CellType.FORMULA) {
cellValue = String.valueOf(cell.getCellFormula());
}
// 空值
? ? ? ? ? ? ? ? ? ? else if (cellType == CellType.BLANK) {
cellValue ="";
}
// BOOLEAN
? ? ? ? ? ? ? ? ? ? else if (cellType == CellType.BOOLEAN) {
cellValue = String.valueOf(cell.getBooleanCellValue());
}
// ERROR
? ? ? ? ? ? ? ? ? ? else if (cellType == CellType.ERROR) {
cellValue = String.valueOf(cell.getErrorCellValue());
}
if (cellValue !=null) {
mapValue.put(String.valueOf(colIndex +1), cellValue);
}
}
if (!mapValue.isEmpty()) {
dataList.add(mapValue);
}
}
}
return dataList;
}
/**
? ? * 數(shù)據(jù)導入到EXCEL中,只支持導入到一個sheet頁,格式為xlsx
*
? ? * @param sheetName
? ? *? ? ? ? ? ? sheet頁名稱
? ? * @param titles
? ? *? ? ? ? ? ? 表格首行字段名稱
? ? * @param dataMap
? ? *? ? ? ? ? ? 數(shù)據(jù)信息
? ? * @param outputStream
? ? * @throws Exception
*/
? ? public static void export2007ExcelByPOI(String sheetName, String[] titles, List> dataMap,
OutputStream outputStream)throws Exception {
// 聲明一個工作簿【SXSSFWorkbook只支持.xlsx格式】
? ? ? ? Workbook workbook =new SXSSFWorkbook(1000);// 內存中只存放1000條
? ? ? ? // 生成一個表格
? ? ? ? Sheet sheet = workbook.createSheet(sheetName);
// 設置表格的默認寬度為18個字節(jié)
? ? ? ? sheet.setDefaultColumnWidth(18);
// 生成一個樣式【用于表格標題】
? ? ? ? CellStyle headStyle = workbook.createCellStyle();
// 設置單元格背景色
? ? ? ? headStyle.setFillForegroundColor(HSSFColorPredefined.SKY_BLUE.getIndex());
headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headStyle.setBorderTop(BorderStyle.THIN);// 單元格上邊框
? ? ? ? headStyle.setBorderBottom(BorderStyle.THIN);// 單元格下邊框
? ? ? ? headStyle.setBorderLeft(BorderStyle.THIN);// 單元格左邊框
? ? ? ? headStyle.setBorderRight(BorderStyle.THIN);// 單元格右邊框
? ? ? ? headStyle.setAlignment(HorizontalAlignment.CENTER);// 單元格水平居中
? ? ? ? headStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 單元格垂直居中
? ? ? ? // 生成字體【用于表格標題】
? ? ? ? Font headFont = workbook.createFont();
headFont.setFontHeightInPoints((short)12);
// 把字體應用到當前樣式
? ? ? ? headStyle.setFont(headFont);
// 生成一個樣式【用于Excel中的表格內容】
? ? ? ? CellStyle contentStyle = workbook.createCellStyle();
// 設置樣式【用于Excel中的表格內容】
? ? ? ? contentStyle.setBorderTop(BorderStyle.THIN);// 單元格上邊框
? ? ? ? contentStyle.setBorderBottom(BorderStyle.THIN);// 單元格下邊框
? ? ? ? contentStyle.setBorderLeft(BorderStyle.THIN);// 單元格左邊框
? ? ? ? contentStyle.setBorderRight(BorderStyle.THIN);// 單元格右邊框
? ? ? ? contentStyle.setAlignment(HorizontalAlignment.CENTER);// 單元格水平居中
? ? ? ? contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 單元格垂直居中
? ? ? ? contentStyle.setWrapText(true);// 單元格自動換行
? ? ? ? // 生成字體
? ? ? ? Font contentFont = workbook.createFont();
// 把字體應用到當前樣式
? ? ? ? contentStyle.setFont(contentFont);
// 產(chǎn)生表格標題行【表格的第一行】
? ? ? ? Row headRow = sheet.createRow(0);
for (int i =0; i < titles.length; i++) {
Cell cell = headRow.createCell(i);
// 設置單元格為文本格式
? ? ? ? ? ? cell.setBlank();
cell.setCellStyle(headStyle);
RichTextString text =new XSSFRichTextString(titles[i]);
cell.setCellValue(text);
}
// 遍歷集合數(shù)據(jù),產(chǎn)生EXCEL行【Excel表格的標題占用了一行】
? ? ? ? int index =1;
for (Map temp : dataMap) {
// 創(chuàng)建一行
? ? ? ? ? ? Row row = sheet.createRow(index);
Set keys = temp.keySet();
for (int i =0; i < keys.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(contentStyle);
Object value = temp.get(String.valueOf(i));
String textValue ="";
// 判斷類型之后進行類型轉換
? ? ? ? ? ? ? ? if (value ==null) {
cell.setCellValue(textValue);
}else if (valueinstanceof Integer) {
cell.setCellValue((Integer)value);
}else if (valueinstanceof Long) {
cell.setCellValue((Long)value);
}else if (valueinstanceof Double) {
cell.setCellValue((Double)value);
}else if (valueinstanceof Boolean) {
cell.setCellValue((Boolean)value);
}else if (valueinstanceof Date) {
DateFormat defaultFormatter =new SimpleDateFormat("yyyy-MM-dd");
textValue = defaultFormatter.format((Date)value);
}else if (valueinstanceof byte[]) {
}else {
textValue = value.toString();
}
// 如果是字符串
? ? ? ? ? ? ? ? if (!"".equals(textValue)) {
RichTextString richString =new XSSFRichTextString(textValue);
// 設置單元格為文本格式
? ? ? ? ? ? ? ? ? ? cell.setBlank();
cell.setCellValue(richString);
}
}
// 行加1
? ? ? ? ? ? index++;
}
workbook.write(outputStream);
outputStream.flush();
workbook.close();
}
}