Java实现Excel文件导入导出(三)

(一)读写Excel文件的几种常用方式

  1. POI
  2. JXL
  3. FESTEXCEL

1.POI简介

APache POI是Apache软件基金会开放源码函式库,POI提供API实现对Microsoft Office格式文档进行读写。HSS是Horrible SpreadSheet Format的缩写,翻译为“讨厌的电子表格格式格式”。通过HSSF可以使用纯Java代码来读取、写入、修改Excel文件。

  1. HSSF:读取Microsoft Excel格式文档
  2. XSSF:读取Microsoft Excel OOXML格式文档
  3. HWPF:读取Microsoft word格式文档
  4. HSLF:读取Microsoft PowerPoint格式文档
  5. HDGH:读取Microsoft Visio格式文档

3.JXL库简介

Java Excel是一个开源的源码项目,可以创建Excel文件,读取Excel中的内容,更新已经存在的Excel文件内容。

4.POI和JXL的区别

如图:
Java实现Excel文件导入导出(三)_第1张图片

5.Excel表简介

如图:
Java实现Excel文件导入导出(三)_第2张图片

(二)JXL的使用

解密JAVA实现Excel导入导出

1.使用JXL创建Excel文件

1.下载—jxl.jar包

2.项目结构目录:
Java实现Excel文件导入导出(三)_第3张图片
3.创建Excel并写入数据

package com.wang;
import java.io.File;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class JxlExcel01 {

    public static void main(String[] args) {

        String[] title = { "编号", "姓名", "性别" };
        // 1.创建Excel文件
        File file = new File("D:\\test01.xls");
        try {
            file.createNewFile();
            // 2.创建工作簿
            WritableWorkbook workbook = Workbook.createWorkbook(file);

            // 3.创建工作表
            WritableSheet sheet = workbook.createSheet("sheet01", 0);
            Label label = null;

            // 4.添加表头数据
            for (int i = 0; i < title.length; i++) {
                label = new Label(i, 0, title[i]);
                sheet.addCell(label);
            }

            // 5.添加行数据
            for (int i =1; i < 10; i++) {
                label = new Label(0,i,""+i);
                sheet.addCell(label);

                label = new Label(1, i, "张三" + i);
                sheet.addCell(label);

                label = new Label(2, i, "男");
                sheet.addCell(label);
            }
            //6.写入数据,关闭工作簿
            workbook.write();
            workbook.close();

        } catch (Exception e) {

            e.printStackTrace();
        }
    }

}

4.读取Excel文件

package com.wang;
import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class JXLReadExcel {

    public static void main(String[] args) {
        try {

            // 1.创建工作簿
            Workbook workbook = Workbook.getWorkbook(new File("D:\\test01.xls"));

            // 2.通过索引获取工作表
            Sheet sheet = workbook.getSheet(0);

            // 3.获取工作表中的数据
            for (int i = 0; i < sheet.getRows(); i++) {
                for (int j = 0; j < sheet.getColumns(); j++) {
                    Cell cell = sheet.getCell(j, i);
                    System.out.print(cell.getContents() + " ");
                }

                System.out.println();
            }
            // 4.关闭workbook对象
            workbook.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

(三)POI的使用

1导入jar包:commons-io-2.2.jar、poi-3.11-20141221.jar

2.使用POI生成Excel文件

package com.wang;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.commons.io.FileUtils;
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;
public class PoiEmportExcel {

    public static void main(String[] args) {

        String[] title = { "编号", "姓名", "性别" };

        // 1.创建工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 2.创建工作表对象
        HSSFSheet sheet = workbook.createSheet();

        // 3.创建第一行
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = null;

        // 4.添加标题栏
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);

        }

        // 5.向表格中插入数据
        for (int i = 1; i <= 10; i++) {
            // 6.创建行对象
            HSSFRow nextrow = sheet.createRow(i);

            // 7.创建单元格对象
            HSSFCell cell2 = nextrow.createCell(0);
            cell2.setCellValue(""+i);

            cell2 = nextrow.createCell(1);
            cell2.setCellValue("张三" + i);

            cell2 = nextrow.createCell(2);
            cell2.setCellValue("男");

        }

        File f = new File("D:\\poi_test.xls");
        try {
            f.createNewFile();
            FileOutputStream stream = FileUtils.openOutputStream(f);
            workbook.write(stream);
            workbook.close();
            System.out.println("成生成Excel表格!");
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

}

3.读取Excel文件

package com.wang;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
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;
public class PoiReadExcel {

    public static void main(String[] args) {

        // 1.引入需要解析的文件
        File f = new File("D:\\poi_test.xls");
        try {

            // 2.创建工作簿,读取文件数据
            HSSFWorkbook workbook = new HSSFWorkbook(FileUtils.openInputStream(f));

            // 3.获取工作表
            // HSSFSheet sheet =workbook.getSheet("sheet0");
            HSSFSheet sheet = workbook.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();

            for (int i = 0; i <= lastRowNum; i++) {
                HSSFRow row = sheet.getRow(i);

                // 4.获取最后一个单元格的序列号
                int lastCellNum = row.getLastCellNum();
                for (int j = 0; j < lastCellNum; j++) {
                    HSSFCell cell = row.getCell(j);

                    // 5.表格中不同数据类型使用不同的方法
                    String value = cell.getStringCellValue();

                    System.out.print(value + "  ");
                }

                System.out.println();
            }

        } catch (IOException e) {

            e.printStackTrace();
        }

    }

}

4.高版本excel文件的创建和读取

1.excel文件以.xls结尾属于:Microsoft Excel1997-2003
2.excel文件以.xlsx结尾属于:Microsoft Excel2007
3.因此不同版本的excel文件使用不同的方法读取
4.HSSFWorkbook改为XSSFWorkbook,HSSFSheet改为XSSFSheet

1.使用XSSFWorkbook和XSSFSheet需要导入jar包:

如图所示:
Java实现Excel文件导入导出(三)_第4张图片

(四)导入模板定制

1.需要使用的jar包:
Java实现Excel文件导入导出(三)_第5张图片
2.student.xml内容如下:


<excel id="student" code="student" name="学生信息导入">
    <colgroup>
        <col index="A" width='17em'>col>
        <col index="B" width='17em'>col>
        <col index="C" width='17em'>col>
        <col index="D" width='17em'>col>
        <col index="E" width='17em'>col>
        <col index="F" width='17em'>col>        
    colgroup>
    <title>
        <tr height="16px">
            <td rowspan="1" colspan="6" value="学生信息导入" />
        tr>
    title>
    <thead>
        <tr height="16px">
            <th value="编号" />
            <th value="姓名" />
            <th value="年龄" />
            <th value="性别" />
            <th value="出生日期" />
            <th value=" 爱好" />            
        tr>
    thead>
    <tbody>
        <tr height="16px" firstrow="2" firstcol="0" repeat="5">
            <td type="string" isnullable="false" maxlength="30" />
            <td type="string" isnullable="false" maxlength="50" />
            <td type="numeric" format="##0" isnullable="false" />
            <td type="enum" format="男,女" isnullable="true" />
            <td type="date" isnullable="false" maxlength="30" />
            <td type="enum" format="足球,篮球,乒乓球" isnullable="true" />
        tr>
    tbody>
excel>

3.生成excel模板

package com.wang;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFFont;
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.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class CreteTemplate {
    /**
     * 创建模板文件
     */
    public static void main(String[] args) {
        //1.获取解析xml文件路径
        String path = System.getProperty("user.dir") + "/bin/student2.xml";
        File file = new File(path);
        SAXBuilder builder = new SAXBuilder();
        try {
            //2.解析xml文件
            Document parse = builder.build(file);

            HSSFWorkbook wb = new HSSFWorkbook();

            HSSFSheet sheet = wb.createSheet("Sheet0");

            //3.获取xml文件跟节点
            Element root = parse.getRootElement();

            //4.获取模板名称
            String templateName = root.getAttribute("name").getValue();

            int rownum = 0;
            int column = 0;
            //5.设置列宽
            Element colgroup = root.getChild("colgroup");
            setColumnWidth(sheet,colgroup);

            //6.设置标题
            Element title = root.getChild("title");
            List trs = title.getChildren("tr");
            for (int i = 0; i < trs.size(); i++) {
                Element tr = trs.get(i);
                List tds = tr.getChildren("td");
                HSSFRow row = sheet.createRow(rownum);
                HSSFCellStyle cellStyle = wb.createCellStyle();
                cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                for(column = 0;column 
                    Element td = tds.get(column);
                    HSSFCell cell = row.createCell(column);
                    Attribute rowSpan = td.getAttribute("rowspan");
                    Attribute colSpan = td.getAttribute("colspan");
                    Attribute value = td.getAttribute("value");
                    if(value !=null){
                        String val = value.getValue();
                        cell.setCellValue(val);
                        int rspan = rowSpan.getIntValue() - 1;
                        int cspan = colSpan.getIntValue() -1;

                        //7.设置字体
                        HSSFFont font = wb.createFont();
                        font.setFontName("仿宋_GB2312");
                        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字体加粗
//                      font.setFontHeight((short)12);
                        font.setFontHeightInPoints((short)12);
                        cellStyle.setFont(font);
                        cell.setCellStyle(cellStyle);

                        //8.合并单元格居中
                        sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan));
                    }
                }
                rownum ++;
            }

            //9.设置表头
            Element thead = root.getChild("thead");
            trs = thead.getChildren("tr");
            for (int i = 0; i < trs.size(); i++) {
                Element tr = trs.get(i);
                HSSFRow row = sheet.createRow(rownum);
                List ths = tr.getChildren("th");
                for(column = 0;column < ths.size();column++){
                    Element th = ths.get(column);
                    Attribute valueAttr = th.getAttribute("value");
                    HSSFCell cell = row.createCell(column);
                    if(valueAttr != null){
                        String value =valueAttr.getValue();
                        cell.setCellValue(value);
                    }
                }
                rownum++;
            }

            //10.设置数据区域样式
            Element tbody = root.getChild("tbody");
            Element tr = tbody.getChild("tr");
            int repeat = tr.getAttribute("repeat").getIntValue();

            List tds = tr.getChildren("td");
            for (int i = 0; i < repeat; i++) {
                HSSFRow row = sheet.createRow(rownum);
                for(column =0 ;column < tds.size();column++){
                    Element td = tds.get(column);
                    HSSFCell cell = row.createCell(column);
                    setType(wb,cell,td);
                }
                rownum++;
            }

            //11.生成Excel导入模板
            File tempFile = new File("D:/" + templateName + ".xls");
            tempFile.delete();
            tempFile.createNewFile();
            FileOutputStream stream = FileUtils.openOutputStream(tempFile);
            wb.write(stream);
            stream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void setType(HSSFWorkbook wb, HSSFCell cell, Element td) {
        Attribute typeAttr = td.getAttribute("type");
        String type = typeAttr.getValue();
        HSSFDataFormat format = wb.createDataFormat();
        HSSFCellStyle cellStyle = wb.createCellStyle();
        if("NUMERIC".equalsIgnoreCase(type)){
            cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
            Attribute formatAttr = td.getAttribute("format");
            String formatValue = formatAttr.getValue();
            formatValue = StringUtils.isNotBlank(formatValue)? formatValue : "#,##0.00";
            cellStyle.setDataFormat(format.getFormat(formatValue));
        }else if("STRING".equalsIgnoreCase(type)){
            cell.setCellValue("");
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cellStyle.setDataFormat(format.getFormat("@"));
        }else if("DATE".equalsIgnoreCase(type)){
            cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
            cellStyle.setDataFormat(format.getFormat("yyyy-m-d"));
        }else if("ENUM".equalsIgnoreCase(type)){
            CellRangeAddressList regions = 
                new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(), 
                        cell.getColumnIndex(), cell.getColumnIndex());
            Attribute enumAttr = td.getAttribute("format");
            String enumValue = enumAttr.getValue();
            //加载下拉列表内容
            DVConstraint constraint = 
                DVConstraint.createExplicitListConstraint(enumValue.split(","));
            //数据有效性对象
            HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
            wb.getSheetAt(0).addValidationData(dataValidation);
        }
        cell.setCellStyle(cellStyle);
    }

    /**
     * 设置列宽
     * */
    private static void setColumnWidth(HSSFSheet sheet, Element colgroup) {
        List cols = colgroup.getChildren("col");
        for (int i = 0; i < cols.size(); i++) {
            Element col = cols.get(i);
            Attribute width = col.getAttribute("width");
            String unit = width.getValue().replaceAll("[0-9,\\.]", "");
            String value = width.getValue().replaceAll(unit, "");
            int v=0;
            if(StringUtils.isBlank(unit) || "px".endsWith(unit)){
                v = Math.round(Float.parseFloat(value) * 37F);
            }else if ("em".endsWith(unit)){
                v = Math.round(Float.parseFloat(value) * 267.5F);
            }
            sheet.setColumnWidth(i, v);
        }
    }

}

你可能感兴趣的:(Java技术)