POI生成excel文件以及预览文件功能

逻辑如下,先得到一个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页面供用户打开了
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章