import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* ZHF 讀取EXCEL模板數據
*
* <dependency>
* <groupId>org.apache.commons</groupId>
* <artifactId>commons-collections4</artifactId>
* <version>4.2</version>
* </dependency>
*/
public class ExportExcelUtil {
public static void main(String[] args) {
ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
List<Map<Integer, String>> rowDataList = new ArrayList<>();
Map<Integer, String> map = new HashMap<>();
map.put(0, "ff");
map.put(1, "AA");
map.put(2, "BB");
map.put(3, "CC");
map.put(4, "DD");
map.put(5, "EE");
Map<Integer, String> map1 = new HashMap<>();
map1.put(0, "數據");
map1.put(1, "數據1");
map1.put(2, "數據3");
map1.put(3, "數據4");
map1.put(4, "數據5");
map1.put(5, "數據6");
rowDataList.add(map);
rowDataList.add(map1);
String path = "D:/file/一覽表.xls";
String realPath = "D:/file/測試";
String newFileName = "一覽表[data]" + System.currentTimeMillis() + ".xlsx";
exportExcelUtil.exportExcel(10, 2, rowDataList, path, realPath, newFileName);
}
/**
* 生成excel
*
* @param rowIndex 從第幾行開始添加
* @param rowCount 添加的行數,一共添加幾行
* @param rowDataList 每行的數據,即每個單元格的數據
* @param path 文件模板路徑
* @param realPath 保存文件的路徑
* @param newFileName 新的文件名
*/
public void exportExcel(int rowIndex, int rowCount, List<Map<Integer, String>> rowDataList, String path, String realPath, String newFileName) {
File newFile = createNewFile(path, realPath, newFileName);
// File newFile = new File("d:/ss.xls");
// 新文件寫入數據,
InputStream is = null;
HSSFWorkbook workbook = null;
HSSFSheet sheet = null;
try {
is = new FileInputStream(newFile);// 將excel文件轉爲輸入流
workbook = new HSSFWorkbook(is);// 創建個workbook,
// 獲取第一個sheet
sheet = workbook.getSheetAt(0);
} catch (Exception e1) {
e1.printStackTrace();
}
if (sheet != null) {
try {
// 寫數據
FileOutputStream fos = new FileOutputStream(newFile);
HSSFRow row = sheet.getRow(rowIndex);
if (row == null) {
row = sheet.createRow(rowIndex);
}
HSSFCell cell = row.getCell(0);
if (cell == null) {
cell = row.createCell(0);
}
for (int m = 0; m < rowCount; m++) {
row = sheet.createRow((int) m + rowIndex);
// 設置 列 數據
for (int i = 0; i < rowDataList.get(m).size(); i++) {
Map<Integer, String> dataMap = rowDataList.get(m);
String value = dataMap.get(i);
if (value.equals("null")) {
value = " ";
}
cell = row.createCell(i);
cell.setCellValue(value);
}
}
workbook.write(fos);
fos.flush();
fos.close();
// 下載
// InputStream fis = new BufferedInputStream(new FileInputStream(
// newFile));
// HttpServletResponse response = ServletActionContext.getResponse();
// byte[] buffer = new byte[fis.available()];
// fis.read(buffer);
// fis.close();
// response.reset();
// response.setContentType("text/html;charset=UTF-8");
// OutputStream toClient = new BufferedOutputStream(
// response.getOutputStream());
// response.setContentType("application/x-msdownload");
// String newName = URLEncoder.encode(
// "報表" + System.currentTimeMillis() + ".xlsx",
// "UTF-8");
// response.addHeader("Content-Disposition",
// "attachment;filename=\"" + newName + "\"");
// response.addHeader("Content-Length", "" + newFile.length());
// toClient.write(buffer);
// toClient.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 刪除創建的新文件
// this.deleteFile(newFile);
}
/**
* 複製文件
*
* @param s 源文件
* @param t 複製到的新文件
*/
public void fileChannelCopy(File s, File t) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(s), 1024);
out = new BufferedOutputStream(new FileOutputStream(t), 1024);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 讀取excel模板,並複製到新文件中供寫入和下載
*
* @param path 文件模板路徑
* @param realPath 保存文件的路徑
* @param newFileName 新的文件名
* @return
*/
public File createNewFile(String path, String realPath, String newFileName) {
// 讀取模板,並賦值到新文件************************************************************
// 文件模板路徑
// String path = "D:/file/一覽表.xls";
File file = new File(path);
// 保存文件的路徑
// String realPath = "D:/file/測試";
// 新的文件名
// String newFileName = "JL07-01儀器設備一覽表[data]" + System.currentTimeMillis() + ".xlsx";
// 判斷路徑是否存在
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdirs();
}
// 寫入到新的excel
File newFile = new File(realPath, newFileName);
try {
newFile.createNewFile();
// 複製模板到新文件
fileChannelCopy(file, newFile);
} catch (Exception e) {
e.printStackTrace();
}
return newFile;
}
/**
* 下載成功後刪除
*
* @param files
*/
private void deleteFile(File... files) {
for (File file : files) {
if (file.exists()) {
file.delete();
}
}
}
下載類:
// 下載word
@RequestMapping(value = "/downWord")
@ResponseBody
public boolean downExcel(HttpServletRequest request, HttpServletResponse response) {
String path = request.getParameter("downUrl");
String regex = "YQSBYLB(.*?).xls";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(path);
while (m.find()) {
String filename = "YQSBYLB" + m.group(1) + ".xls";
ExcelExportUtil excelExport2 = new ExcelExportUtil();
return excelExport2.downLoadFile(path, response, request, filename, "xls");
}
return false;
}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class ExcelExportUtil {
/**
* 下載 excel
*
* @param filePath
* @param response
* @param request
* @param fileName
* @param fileType
* @return
*/
public boolean downLoadFile(String filePath,
HttpServletResponse response, HttpServletRequest request,
String fileName, String fileType) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
String downLoadPath = filePath;
long fileLength = new File(downLoadPath).length();
if ("pdf".equals(fileType)) {
response.setContentType("application/pdf;charset=UTF-8");
} else if ("xls".equals(fileType)) {
response.setContentType("application/x-msdownload;");
} else if ("doc".equals(fileType)) {
response.setContentType("application/msword;charset=UTF-8");
}
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
}