Excel创建并下载,poi和jxl两种方式

构建Excel并下载

<body>
<ta:box>
    <ta:fieldset id="flt1" key="excel操作(包含常用所有样式设置)" cols="4">
        <ta:buttonLayout>
            <ta:button id="btn_writeExcel_jxl" key="(jxl)构建excel并下载" onClick="fnWriteExcel(1)"/>
            <ta:button id="btn_writeExcel_poi" key="(poi)构建excel并下载" onClick="fnWriteExcel(2)"/>
        </ta:buttonLayout>
    </ta:fieldset>
    <form id="form1" method="post" enctype="multipart/form-data" style="display: none">
        <input id="form1Submit" type="submit" value="forfile" />
    </form>
</ta:box>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function () {
        $("body").taLayout();
    });

    function fnWriteExcel(id) {
        if(id == "1"){
            $("#form1").attr("action","excelController!writeExcelByJxl.do");
        }else if(id == "2"){
            $("#form1").attr("action","excelController!writeExcelByPoi.do");
        }else{
            return;
        }
        $("#form1Submit").click();
    }

</script>

---------------------------------------------------------------------------------------------------------

/**
 * jxl构建excel
 */
@RequestMapping("excelController!writeExcelByJxl.do")
public String writeExcelByJxl() throws Exception {
     HttpServletResponse response = getResponse();
     OutputStream os = response.getOutputStream();// 取得输出流
     response.reset();// 清空输出流
     response.setHeader("Content-disposition", "attachment; filename=test.xls");// 设定输出文件头
     response.setContentType("application/msexcel");// 定义输出类型

     // 建立excel文件
     WritableWorkbook wbook = Workbook.createWorkbook(os);

     // 生成sheet,第一个参数代表名称,第二个参数代表顺序,从0开始,如果两个sheet顺序int值一样,则以第二个为准
     // 也就是说int为0 , 1和分别为1 , 1,效果是一样的
     WritableSheet wsheet = wbook.createSheet("第一个sheet名称", 0);
     WritableSheet wsheet2 = wbook.createSheet("第二个sheet名称", 1);

     // 分别给1,2,3,4列设置不同的宽度
     wsheet.setColumnView(0, 4);
     wsheet.setColumnView(1, 8);
     wsheet.setColumnView(2, 12);
     wsheet.setColumnView(3, 20);
     // 分别给1,2,3,4列设置不同的高度
     wsheet.setRowView(0, 400);
     wsheet.setRowView(1, 500);
     wsheet.setRowView(2, 600);
     wsheet.setRowView(3, 700);

     // 提前设置样式1
     // 在设置某一个位置数据时,可以把这个样式作为第四个参数,设置这个位置数据的样式
     WritableFont wfont1 = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.RED);
     WritableCellFormat wcfFC1 = new WritableCellFormat(wfont1);
     // 添加背景色
     wcfFC1.setBackground(Colour.AQUA);
     // 设置边框
     wcfFC1.setBorder(Border.ALL, BorderLineStyle.DASH_DOT);
     // 设置自动换行
     wcfFC1.setWrap(true);
     // 设置文字居中对齐方式
     wcfFC1.setAlignment(Alignment.CENTRE);
     // 设置垂直居中
     wcfFC1.setVerticalAlignment(VerticalAlignment.CENTRE);

     // 提前设置样式2
     WritableFont wfont2 = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.RED);
     WritableCellFormat wcfFC2 = new WritableCellFormat(wfont2);
     wcfFC2.setBackground(Colour.BLUE);

     // 开始设置某处位置的数据
     // 定义一个单元格,某列,某行,内容值,单元格样式(可以不写),然后设置到某一个sheet中
     wsheet.addCell(new Label(2, 0, "开发部xxxxxx", wcfFC1));
     wsheet.addCell(new Label(3, 1, "java基础xxxxx", wcfFC1));
     wsheet.addCell(new Label(0, 2, "序号xxxxxx", wcfFC2));
     wsheet.addCell(new Label(1, 2, "知识点xxxxx", wcfFC2));
     Map<String, String> map = new HashMap<String, String>();
     map.put("one", "servletxxxxx");
     map.put("two", "io流xxxxxx");
     map.put("three", "反射xxxxxx");
     map.put("four", "多线程xxxxxx");
     int count = 0;
     for (String key : map.keySet()) {
         wsheet.addCell(new Label(0, count + 3, key));
         wsheet.addCell(new Label(1, count + 3, map.get(key)));
         count++;
     }

     // 主体内容生成结束
     wbook.write(); // 写入文件
     wbook.close();
     os.close(); // 关闭流

     return JSON;
}

------------------------------------------------------------------------------------------------------------------------------

/**
 * poi构建excel
 */
@RequestMapping("excelController!writeExcelByPoi.do")
public String writeExcelByPoi() throws Exception{
    HttpServletResponse response = getResponse();
    OutputStream os = response.getOutputStream();// 取得输出流
    response.reset();// 清空输出流
    response.setHeader("Content-disposition", "attachment; filename=test.xls");// 设定输出文件头
    response.setContentType("application/msexcel");// 定义输出类型

    // 创建新的Excel 工作簿
    HSSFWorkbook workbook = new HSSFWorkbook();

    // 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
    HSSFSheet sheet = workbook.createSheet();
    //HSSFSheet sheet = workbook.createSheet("SheetName");

    // 用于格式化单元格的数据
    HSSFDataFormat format = workbook.createDataFormat();

    // 创建新行(row),并将单元格(cell)放入其中. 行号从0开始计算.
    HSSFRow row = sheet.createRow((short) 1);

    // 设置字体
    HSSFFont font = workbook.createFont();
    font.setFontHeightInPoints((short) 20); //字体高度
    font.setColor(HSSFFont.COLOR_RED); //字体颜色
    font.setFontName("黑体"); //字体
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //宽度
    font.setItalic(true); //是否使用斜体
    // font.setStrikeout(true); //是否使用划线

    // 设置单元格类型
    HSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setFont(font);
    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平布局:居中
    cellStyle.setWrapText(true);

    // 添加单元格注释
    // 创建HSSFPatriarch对象,HSSFPatriarch是所有注释的容器.
    HSSFPatriarch patr = sheet.createDrawingPatriarch();
    // 定义注释的大小和位置,详见文档
    HSSFComment comment = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5));
    // 设置注释内容
    comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
    // 设置注释作者. 当鼠标移动到单元格上是可以在状态栏中看到该内容.
    comment.setAuthor("Xuys.");

    // 创建单元格
    HSSFCell cell = row.createCell((short) 1);
    HSSFRichTextString hssfString = new HSSFRichTextString("Hello World!");
    cell.setCellValue(hssfString);//设置单元格内容
    cell.setCellStyle(cellStyle);//设置单元格样式
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);//指定单元格格式:数值、公式或字符串
    cell.setCellComment(comment);//添加注释

    //格式化数据
    row = sheet.createRow((short) 2);
    cell = row.createCell((short) 2);
    cell.setCellValue(11111.25);
    cellStyle = workbook.createCellStyle();
    cellStyle.setDataFormat(format.getFormat("0.0"));
    cell.setCellStyle(cellStyle);

    row = sheet.createRow((short) 3);
    cell = row.createCell((short) 3);
    cell.setCellValue(9736279.073);
    cellStyle = workbook.createCellStyle();
    cellStyle.setDataFormat(format.getFormat("#,##0.0000"));
    cell.setCellStyle(cellStyle);


    sheet.autoSizeColumn((short)0); //调整第一列宽度
    sheet.autoSizeColumn((short)1); //调整第二列宽度
    sheet.autoSizeColumn((short)2); //调整第三列宽度
    sheet.autoSizeColumn((short)3); //调整第四列宽度

    // 主体内容生成结束
    workbook.write(os); // 写入文件
    workbook.close();
    os.close(); // 关闭流

    return JSON;
}

-------------------------------------------------------------------------------------------------------

解析Excel

思路就是首先获取每一个sheet,每一行,每一列的那个数据,最终每一行就会对应一个String类型的数组,返回List<String[]>
我这个做了一点更改,每一个数据还加上了对应的sheet名字

public class POIUtil {

    private final static String xls = "xls";
    private final static String xlsx = "xlsx";

    /**
     * 读入excel文件,解析后返回
     * @param file
     * @throws IOException
     */
    public static List<String[]> readExcel(MultipartFile file) throws Exception {
        //检查文件
        checkFile(file);
        //获得Workbook工作薄对象
        Workbook workbook = getWorkBook(file);
        //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
        List<String[]> list = new ArrayList<String[]>();
        if(workbook != null){
            for(int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++){
                //获得当前sheet工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if(sheet == null){
                    continue;
                }
                //获得当前sheet的开始行
                int firstRowNum  = sheet.getFirstRowNum();
                //获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();
                //循环除了第一行的所有行
                for(int rowNum = firstRowNum+1; rowNum <= lastRowNum; rowNum++){
                    //获得当前行
                    Row row = sheet.getRow(rowNum);
                    if(row == null){
                        continue;
                    }
                    //获得当前行的开始列
                    int firstCellNum = row.getFirstCellNum();
                    //获得当前行的列数
                    int lastCellNum = row.getPhysicalNumberOfCells();
                    String[] cells = new String[row.getPhysicalNumberOfCells() + 1];
                    //循环当前行
                    for(int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++){
                        Cell cell = row.getCell(cellNum);
                        cells[cellNum] = getCellValue(cell);
                    }
                    cells[row.getPhysicalNumberOfCells()] = sheet.getSheetName();
                    list.add(cells);
                }

            }
            workbook.close();
        }
        return list;
    }

    private static void checkFile(MultipartFile file) throws IOException {
        //判断文件是否存在
        if(null == file){
            throw new FileNotFoundException("文件不存在!");
        }
        //获得文件名
        String fileName = file.getOriginalFilename();
        //判断文件是否是excel文件
        if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
            throw new IOException(fileName + "不是excel文件");
        }
    }

    private static Workbook getWorkBook(MultipartFile file) throws Exception{
        //获得文件名
        String fileName = file.getOriginalFilename();
        //创建Workbook工作薄对象,表示整个excel
        Workbook workbook = null;
        try {
            //获取excel文件的io流
            InputStream is = file.getInputStream();
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if(fileName.endsWith(xls)){
                //2003
                workbook = new HSSFWorkbook(is);
            }else if(fileName.endsWith(xlsx)){
                //2007
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            throw new AppException("获取对应的Excel对象出错!" + e.getMessage());
        }
        return workbook;
    }

    private static String getCellValue(Cell cell) throws Exception{
        String cellValue = "";
        if(cell == null){
            return cellValue;
        }
        //把数字当成String来读,避免出现1读成1.0的情况
        if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        //判断数据的类型
        switch (cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC: //数字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

}

猜你喜欢

转载自blog.csdn.net/blossomfzq/article/details/82868339