邏輯如下,先得到一個list,然後遍歷list的詳情放到對應的excel表中,我這裏生成的是xlsx文件。如果是xls文件代碼會稍微不同,暫時不貼出了,測試例子如下
//生成excel文件
public static String list2Excel(List<Map> list,String folderPath) throws Exception {
Workbook wb = new XSSFWorkbook();
String[] title = {"序號","姓名","地址"};//標題行字段
Sheet stuSheet = wb.createSheet();
Row titleRow = stuSheet.createRow(0);//獲取表頭行
//創建單元格,設置style居中,字體,單元格大小等
CellStyle style = wb.createCellStyle();
Cell cell = null;
//把已經寫好的標題行寫入excel文件中
for (int i = 0; i < title.length; i++) {
cell = titleRow.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
//把查詢得到的結果寫入excel文件中
Row row = null;
for (int i = 0; i < list.size(); i++) {
row = stuSheet.createRow(i + 1);
//把值一一寫進單元格里,設置第一列爲自動遞增的序號
row.createCell(0).setCellValue(i + 1);
row.createCell(1).setCellValue(list.get(i).get("name").toString());
row.createCell(2).setCellValue(list.get(i).get("address").toString());
CreationHelper creationHelper = wb.getCreationHelper();
Hyperlink link = creationHelper.createHyperlink(Hyperlink.LINK_URL);
String url = "http://www.baidu.com";
link.setAddress(url);
row.getCell(2).setHyperlink(link);//設置超鏈接
Font font = wb.createFont();
font.setColor(IndexedColors.BLUE.getIndex());
CellStyle cellStyle = wb.createCellStyle();
cellStyle.cloneStyleFrom(row.getCell(2).getCellStyle());
cellStyle.setFont(font);
row.getCell(2).setCellStyle(cellStyle);//設置某一行的字體顏色
}
//設置單元格寬度自適應
for (int i = 0; i < title.length; i++) {
stuSheet.autoSizeColumn(i, true);
//stuSheet.setColumnWidth(i, stuSheet.getColumnWidth(i));
}
stuSheet.setColumnWidth(1, 60 * 256);//設置第一列固定寬度
File folder = new File(folderPath);
//如果文件夾不存在創建對應的文件夾
if (!folder.exists()) {
folder.mkdirs();
}
String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+ ".xlsx";
String savePath = folderPath + File.separator + fileName;
OutputStream fileOut = new FileOutputStream(savePath);
wb.write(fileOut);
fileOut.close();
return savePath;
}
第二步就是生成預覽的文件,其實就是讀取剛纔生成的excel然後重新生成一個html文件,用戶就可以在瀏覽器打開預覽的文件看了
//生成預覽文件方法
public static String xlxsToHtml(String folderPath,String excelPath) throws Exception {
Workbook workbook = null;
String previewName = System.currentTimeMillis()+".html";//預覽的文件名
InputStream is = new FileInputStream(excelPath);
try {
String html = "";
workbook = new XSSFWorkbook(is);
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
html += "<html lang=\"en\">";
html += "<head>";
html += "<meta charset=\"UTF-8\">";
html += " <meta name=\"keywords\" content=\"\">";
html += "<meta name=\"description\" content=\"\">";
html += "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">";
html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";
html += "<style>";
html += "table th{";
html += "font-weight: normal;";
html += "font-size: 14px;";
html += "color: #333;";
html += "background: #E5E5E5;";
html += "}";
html += "table td{";
html += "font-size: 14px;";
html += "color: #333;";
html += "}";
html += "</style>";
html += "</head>";
html += "<body>";
int firstRowIndex = sheet.getFirstRowNum();
int lastRowIndex = sheet.getLastRowNum();
if (lastRowIndex>5){
lastRowIndex = 5;//只能預覽5條數據
}
html += "<table border='1' cellspacing='0' align='left'>";
Row firstRow = sheet.getRow(firstRowIndex);
for (int i = firstRow.getFirstCellNum(); i < firstRow.getLastCellNum(); i++) {
Cell cell = firstRow.getCell(i);
String cellValue = getCellValue(cell, true);
html += "<th>" + cellValue + "</th>";
}
// 行
for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
Row currentRow = sheet.getRow(rowIndex);
html += "<tr>";
if (currentRow != null) {
int firstColumnIndex = currentRow.getFirstCellNum();
int lastColumnIndex = currentRow.getLastCellNum();
for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
Cell currentCell = currentRow.getCell(columnIndex);
String currentCellValue = getCellValue (currentCell, true);
if (columnIndex==0){
html += "<td>" + rowIndex + "</td>";//行號
}else if (columnIndex==1){
html += "<td style='width:480px;'>" + currentCellValue + "</td>";
}else if (columnIndex == 2){
Hyperlink hyperLink = currentCell.getHyperlink();//獲取超鏈接的地址
if (hyperLink !=null){
html += "<th><a target='_blank' href="+hyperLink.getAddress()+" >" + currentCellValue + "</a></td>";
}
}
else{
html += "<td>" + currentCellValue + "</td>";
}
}
} else {
html += " ";
}
html += "</tr>";
}
html += "</table>";
html += "</body>";
html += "</html>";
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource();
StreamResult streamResult = new StreamResult(outStream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
outStream.close();
FileUtils.writeStringToFile(new File(folderPath, previewName), html, "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return previewName;
}
private static String getCellValue(Cell cell, boolean treatAsStr) {
if (cell == null) {
return "";
}
if (treatAsStr) {
cell.setCellType(Cell.CELL_TYPE_STRING);
}
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
} else {
return String.valueOf(cell.getStringCellValue());
}
}
測試類調用
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public static void main(String[] args) {
List<Map> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Map map = new HashMap();
map.put("name","test"+i);
map.put("address","發展路"+i);
list.add(map);
}
String folderPath = "E:excel";
try {
String excelPath = list2Excel(list,folderPath);
System.out.println(excelPath);
String previewName = xlxsToHtml(folderPath,excelPath);
System.out.println(previewName);
}catch (Exception e){
e.printStackTrace();
}
}
生成的excel文件效果
假如用戶需要在瀏覽器通過網址的方式打開預覽文件或者excel,這個時候就需要用到nginx的location屬性來配置了,可以加一個這樣的配置。意思就是以數字開頭,.html或者.xlsx結尾的網址就會來到E:/excel/下匹配。$1對應[0-9]+,$2對應html|xlsx
location ~ /([0-9]+)\.(html|xlsx)$ {
alias E:/excel/$1.$2;
}
nginx測試效果如下,這樣就可以把url寫在web頁面供用戶打開了