摘要
Poi导出Excel有多种java类可以实现,但实现的原理几乎都是相同的:
1.创建工作博 2.创建sheet 3.创建行(row) 4.创建cell单元格 5.将数据加入单元格。下面是总结的代码。
代码结构
**导出方法: **
public static void exportExcelImg(HttpServletResponse response, String fileName, ExcelData data) throws Exception {}
**封装实体类: **
public class ExcelData implements Serializable{}
代码
*ExcelData:*用来封装导出数据的实体类
*exportExcelImg(…):*导出方法
package com.zhaopin.pinebase.util;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import com.zhaopin.pinebase.modules.zhaopin.form.ExcelData;
public class ExportExcelUtils {
public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception {
// 告诉浏览器用什么软件可以打开此文件
response.setHeader("content-Type", "application/vnd.ms-excel");
// 下载文件的默认名称
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
exportExcel(data, response.getOutputStream());
}
//导出带有图片的excel
public static void exportExcelImg(HttpServletResponse response, String fileName,
ExcelData data) throws Exception {
FileOutputStream fileOut = null;
BufferedImage bufferImg = null;//logo
ByteArrayOutputStream byteArrayOut = null; //读进图片
HttpURLConnection conn =null;
response.setHeader("content-Type", "application/vnd.ms-excel");// 告诉浏览器用什么软件可以打开此文件
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
XSSFWorkbook wb = new XSSFWorkbook();
try {
String sheetName = data.getName();
if (null == sheetName) {
sheetName = "Sheet1";
}
XSSFSheet sheet = wb.createSheet(sheetName);
int width = 25;
sheet.setColumnWidth(0, 256*width+100);//列宽