- 设置占位符的数值
- EXCEL导出工具类
package com.report.util.excle2;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Number;
import jxl.write.*;
import org.springframework.core.io.ClassPathResource;
import sun.misc.BASE64Encoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
public class ExcelTool {
public static void exportExcel(String year, String other, String path, List<?> list, HttpServletRequest request, HttpServletResponse response, String fileName) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("year", year);
map.put("other", other);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
map.put("yyyy-MM-dd", sdf.format(date));
map.put("list", list);
exportExcel(path, map, request, response ,fileName);
}
private static String getFileName(String fileName , HttpServletRequest request) throws UnsupportedEncodingException {
String userAgent = request.getHeader("User-Agent");
if ("Edge".contains(userAgent)) {
fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
}else if ("Chrome".contains(userAgent)) {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}else if ("Firefox".contains(userAgent)) {
fileName = "=?utf-8?b?"+new BASE64Encoder().encode(fileName.getBytes("utf-8"))+"?=";
}else if ("Trident".contains(userAgent)) {
fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
}else {
fileName = new String(fileName.getBytes("gbk"),"ISO8859-1");
}
return fileName;
}
private static void exportExcel(String template, Map<String, Object> datas, HttpServletRequest request, HttpServletResponse response, String fileName) throws Exception {
ServletOutputStream out = null;
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
ClassPathResource classPathResource = new ClassPathResource(template);
InputStream is = classPathResource.getInputStream();
try {
if (is != null) {
Workbook book = Workbook.getWorkbook(is);
File tempFile = File.createTempFile("temp", ".xls");
WritableWorkbook wWorkbook = Workbook.createWorkbook(tempFile, book);
generateExpData(book, wWorkbook, datas);
generateEachData(book, wWorkbook, datas);
wWorkbook.write();
wWorkbook.close();
bis = new BufferedInputStream(new FileInputStream(tempFile));
response.addHeader("Content-Disposition", "attachment; filename=" + getFileName(fileName, request));
response.addHeader("Content-Type","application/octet-stream;charset=utf-8");
out=response.getOutputStream();
byte[] data = new byte[1024];
int bytes = 0;
bos = new BufferedOutputStream(out);
while ((bytes = bis.read(data, 0 , data.length)) != -1) {
bos.write(data, 0, bytes);
}
bos.flush();
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally{
if(bos!=null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void generateExpData(Workbook book, WritableWorkbook wWorkbook, Map<String, Object> datas) throws Exception {
List<ExcelCells> expcells = search("${", book);
for (ExcelCells cell : expcells) {
wWorkbook.getSheet(cell.getSheetIndex()).addCell(getValueByExp(cell, datas));
}
}
private static void generateEachData(Workbook book, WritableWorkbook wWorkbook, Map<String, Object> datas) throws Exception {
List<ExcelCells> each = search("each.", book);
Map<String, List<ExcelCells>> map = new LinkedHashMap<String, List<ExcelCells>>();
for (ExcelCells cell : each) {
String[] array = cell.getCell().getContents().trim().split("\\.");
if (array.length >= 3) {
String key = array[0] + "." + array[1];
List<ExcelCells> list = map.get(key);
if (list == null) {
list = new ArrayList<ExcelCells>();
map.put(key, list);
}
list.add(cell);
}
}
Iterator<String> iterator = map.keySet().iterator();
int insertrow = 0;
int lastSheetIndex = -1;
while (iterator.hasNext()) {
String key = iterator.next();
List<ExcelCells> list = map.get(key);
int sheetIndex = list.get(0).getSheetIndex();
if(lastSheetIndex != -1 && lastSheetIndex != sheetIndex) insertrow = 0;
lastSheetIndex = sheetIndex;
int startRow = list.get(0).getCell().getRow() + insertrow;
String[] array = list.get(0).getCell().getContents().trim().split("\\.");
if (array.length > 0) {
String indexName = array[1];
Object data = datas.get(indexName);
if (data != null && !data.getClass().getName().equals(List.class.getName()) && !data.getClass().getName().equals(ArrayList.class.getName())) {
throw new Exception("数据:" + indexName + "不是一个集合类!");
}
List<Object> rowsData = (List<Object>) data;
if (rowsData != null && rowsData.size() > 0) {
for (int i = 0; i < rowsData.size(); i++) {
if (i == 0) {
for (ExcelCells cell : list) {
wWorkbook.getSheet(sheetIndex).addCell(getValueByEach(cell, rowsData.get(i), startRow, cell.getCell().getColumn()));
}
continue;
}
wWorkbook.getSheet(sheetIndex).insertRow(startRow + i);
for (ExcelCells cell : list) {
wWorkbook.getSheet(sheetIndex).addCell(getValueByEach(cell, rowsData.get(i), startRow + i, cell.getCell().getColumn()));
}
insertrow++;
}
} else {
for (ExcelCells cell : list) {
wWorkbook.getSheet(sheetIndex).addCell(getValueByEach(cell, null, startRow, cell.getCell().getColumn()));
}
}
}
}
}
private static WritableCell getValueByExp(ExcelCells cells, Map<String, Object> datas) {
WritableCell writableCell = null;
List<Object> values = new ArrayList<Object>();
List<String> exps = cells.getExps();
String old_c = cells.getCell().getContents();
for (String exp : exps) {
String[] names = exp.replace("${", "").replace("}", "").split("\\.");
Object object = null;
for (String name : names) {
if (object == null)
object = ObjectCustomUtil.getValueByFieldName(name, datas);
else
object = ObjectCustomUtil.getValueByFieldName(name, object);
}
if (!old_c.isEmpty()) {
while (old_c.indexOf(exp) != -1)
old_c = old_c.replace(exp, object.toString());
}
}
writableCell = getWritableCellByObject(cells.getCell().getRow(), cells.getCell().getColumn(), old_c);
writableCell.setCellFormat(cells.getCell().getCellFormat());
return writableCell;
}
private static WritableCell getValueByEach(ExcelCells cells, Object datas, int rows, int column) {
WritableCell writableCell = null;
if (datas != null) {
List<Object> values = new ArrayList<Object>();
String[] exps = cells.getCell().getContents().trim().split("\\.");
Object object = null;
for (int i = 2; i < exps.length; i++) {
if (object == null)
object = ObjectCustomUtil.getValueByFieldName(exps[i], datas);
else
object = ObjectCustomUtil.getValueByFieldName(exps[i], object);
}
writableCell = getWritableCellByObject(rows, column, object);
} else {
writableCell = getWritableCellByObject(rows, column, null);
}
writableCell.setCellFormat(cells.getCell().getCellFormat());
return writableCell;
}
private static WritableCell getWritableCellByObject(int beginRow, int beginColumn, Object obj) {
WritableCell cell = null;
if (obj == null)
return new Label(beginColumn, beginRow, "");
if (obj.getClass().getName().equals(String.class.getName())) {
cell = new Label(beginColumn, beginRow, obj.toString());
} else if (obj.getClass().getName().equals(int.class.getName()) || obj.getClass().getName().equals(Integer.class.getName())) {
cell = new Number(beginColumn, beginRow, Integer.parseInt(obj.toString()));
} else if (obj.getClass().getName().equals(float.class.getName()) || obj.getClass().getName().equals(Float.class.getName())) {
cell = new Number(beginColumn, beginRow, Float.parseFloat(obj.toString()));
} else if (obj.getClass().getName().equals(double.class.getName()) || obj.getClass().getName().equals(Double.class.getName())) {
cell = new Number(beginColumn, beginRow, Double.parseDouble(obj.toString()));
} else if (obj.getClass().getName().equals(long.class.getName()) || obj.getClass().getName().equals(Long.class.getName())) {
cell = new Number(beginColumn, beginRow, Long.parseLong(obj.toString()));
} else if (obj.getClass().getName().equals(Date.class.getName())) {
cell = new DateTime(beginColumn, beginRow, (Date)obj);
} else {
cell = new Label(beginColumn, beginRow, obj.toString());
}
return cell;
}
private static ExcelCells searchFirstText(String text, Workbook book) {
ExcelCells Rcell = null;
Sheet[] sheets = book.getSheets();
if (sheets != null) {
int sheetIndex = 0;
for (Sheet sheet : sheets) {
if (sheet != null) {
int rows = sheet.getRows();
if (rows > 0) {
for (int i = 0; i < rows; i++) {
Cell[] cells = sheet.getRow(i);
if (cells != null) {
for (Cell cell : cells) {
if (cell != null && !StringUtils.isNull(cell.getContents())) {
String contents = cell.getContents();
if (contents.equals(text))
return new ExcelCells(sheet, cell, sheetIndex);
}
}
}
}
}
}
sheetIndex++;
}
}
return Rcell;
}
private static List<ExcelCells> search(String text, Workbook book) {
List<ExcelCells> rcells = new ArrayList<ExcelCells>();
Sheet[] sheets = book.getSheets();
if (sheets != null)
for (Sheet sheet : sheets) {
if (sheet != null) {
int rows = sheet.getRows();
if (rows > 0) {
for (int i = 0; i < rows; i++) {
Cell[] cells = sheet.getRow(i);
if (cells != null) {
for (Cell cell : cells) {
if (cell != null && !StringUtils.isNull(cell.getContents())) {
String contents = cell.getContents();
if (contents.indexOf(text) != -1)
rcells.add(new ExcelCells(sheet, cell));
}
}
}
}
}
}
}
return rcells;
}
}
- 模板样式
- POM
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
- 总结:不是原创。结合自己整理。