ExcelExportUtil

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;

import com.jfinal.plugin.activerecord.Model;

public class ExcelExportUtil{
    /**
     * @param response
     * @param request
     * @param filename  导出的文件名
     * @param titles 标题列和列名的对应.column:列名,title标题名
     * @param records 记录
     */
    @SuppressWarnings("unchecked")
    public static <M extends Model<M>> void exportByRecord(HttpServletResponse response,HttpServletRequest request,String filename,List<Pair> titles, List<M> records){
        exportByRecord(response, request, filename, new SheetData<M>(titles, records));
    }

    /**
     * @param response
     * @param request
     * @param filename  导出的文件名
     * @param sheetDatas 产生一个sheet需要的数据
     */
    public static <M extends Model<M>> void exportByRecord(HttpServletResponse response,HttpServletRequest request,String filename,SheetData<M>... sheetDatas){
        HSSFWorkbook wb = new HSSFWorkbook();                               
        //标题行的style
        CellStyle titleCellStyle = wb.createCellStyle();                    
        titleCellStyle.setAlignment(CellStyle.ALIGN_CENTER);                //居中
        titleCellStyle.setWrapText(true);                                   //自动换行  
        Font font = wb.createFont();
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);                       //加粗
        font.setFontName("微软雅黑");
        titleCellStyle.setFont(font);

        //内容行的style
        CellStyle cellStyle = wb.createCellStyle();                 
        cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  //垂直居中
        cellStyle.setWrapText(true);    
        Font font2 = wb.createFont();
        font2.setFontName("微软雅黑");
        cellStyle.setFont(font2);   

        //多张sheet
        for (SheetData<M> sheetData : sheetDatas) {
            List<Pair> titles = sheetData.titles;
            List<M> records = sheetData.records;
            HSSFSheet sheet = wb.createSheet();
            int rowIndex = 0,cellIndex=0;
            HSSFRow row = null;
            HSSFCell cell = null;

            //创建标题行
            row = sheet.createRow(rowIndex);
            row.setHeight((short)450);
            rowIndex++;

            for (Pair pair : titles) {
                cell = row.createCell(cellIndex);
                cell.setCellStyle(titleCellStyle);              //设置样式
                cellIndex++;
                cell.setCellValue(pair.title);
            }

            //处理每一行
            for (M record : records) {
                row = sheet.createRow(rowIndex);
                row.setHeight((short)450);
                rowIndex++;
                cellIndex = 0;

                for (Pair pair : titles) {
                    cell = row.createCell(cellIndex);
                    cell.setCellStyle(cellStyle);               //设置样式
                    cellIndex++;

                    Object value = record.get(pair.column);

                    if(value!=null){
                        cell.setCellValue(value.toString());
                    }
                }
            }
        }
        //序号
        writeStream(filename, wb, response,request);
    }

    /**
     * 写到输出流
     */
    private static void writeStream(String filename, HSSFWorkbook wb, HttpServletResponse response, HttpServletRequest request){
        try{
            String agent = request.getHeader("USER-AGENT");
            filename += ".xls";
            filename.replaceAll("/", "-");
            // filename = new String(filename.getBytes("gbk"),"ISO8859_1");

            if (agent.toLowerCase().indexOf("firefox")>0){
                filename = new String(filename.getBytes("utf-8"), "iso-8859-1");
            }else{
                filename = URLEncoder.encode(filename, "UTF-8");
            }

            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();

        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 标题列和列名的对应
     */
    public static class Pair {
        public String column;
        public String title;

        public Pair(String column,String title){
            this.column = column;
            this.title = title;
        }
    }

    /**
     * 创建一个sheet需要的数据
     */
    public static class SheetData<M extends Model<M>>{
        public List<Pair> titles;
        public List<M> records;

        public SheetData(List<Pair> titles, List<M> records) {
            this.titles = titles;
            this.records = records;
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的示例代码,演示了如何使用ExcelExportUtil工具类导出一个包含学生信息的Excel文件: ```java import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import com.github.crab2died.ExcelUtils; public class ExcelExportExample { public static void main(String[] args) { // 创建学生列表 List<Student> students = new ArrayList<>(); students.add(new Student(1, "张三", 90)); students.add(new Student(2, "李四", 85)); students.add(new Student(3, "王五", 95)); // 导出Excel文件 try { FileOutputStream fos = new FileOutputStream("students.xlsx"); ExcelUtils.getInstance().exportObjects2Excel(students, Student.class, true, fos); fos.close(); System.out.println("Excel文件导出成功!"); } catch (Exception e) { e.printStackTrace(); } } // 学生类 static class Student { private int id; private String name; private int score; public Student(int id, String name, int score) { this.id = id; this.name = name; this.score = score; } // getter和setter方法省略 } } ``` 在这个示例中,我们创建了一个包含学生信息的List对象,然后使用ExcelExportUtil工具类的`exportObjects2Excel`方法将这些学生信息导出为一个名为"students.xlsx"的Excel文件。导出过程中,我们需要提供学生类的Class对象以及输出流用于写入Excel文件。 请注意,为了使Excel文件中的表头与学生类的属性名对应,我们将`true`传递给`exportObjects2Excel`方法的第三个参数,这样工具类会自动获取类的属性名作为表头。 这只是一个简单的示例,你可以根据自己的需求来使用ExcelExportUtil工具类进行更复杂的Excel导出操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值