1. 程式人生 > >解析xml模板匯出Excel

解析xml模板匯出Excel

1.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.tiglle</groupId>
  <artifactId
>
excel</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl --> <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId
>
<version>2.6.12</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version
>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/jdom/jdom --> <dependency> <groupId>jdom</groupId> <artifactId>jdom</artifactId> <version>1.1</version> </dependency> </dependencies> </project>

2.excelConf.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 利用xml解析技術,定義匯出Excel的模板:包含各種樣式 -->
<excel id="student" name="student" excelName="學生資訊匯入">
    <columns>
        <column index="A" width="17em"></column>
        <column index="B" width="17em"></column>
        <column index="C" width="17em"></column>
        <column index="D" width="17em"></column>
        <column index="E" width="17em"></column>
        <column index="F" width="17em"></column>
    </columns>

    <title rowspan="1" colspan="6">學生資訊</title>

    <table>
        <tr height="16px">
            <td>編號</td>
            <td>姓名</td>
            <td>年齡</td>
            <td>生日</td>
            <td>愛好</td>
            <td>性別</td>
        </tr>
    </table>
    <format height="16px" firstRow="2" finstCol="0" repeat="5">
        <td type="String" allowNull="false" maxLength="30"></td>
        <td type="String" allowNull="false" maxLength="40"></td>
        <td type="number" allowNull="false" format="##0"></td>
        <td type="date" allowNull="true" maxLength="30"></td>
        <td type="String" allowNull="true" maxLength="30"></td>
        <td type="enum" allowNull="false" format="男,女"></td>
    </format>
</excel>

3.GenerateExcelByTemplate.java

package com.tiglle.readXml;

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 * 根據xml配置(格式,樣式,標題等)
 * 使用jdom讀取xml並生成Excle
 * @author Administrator
 *
 */
public class GenerateExcelByTemplate {

    public static void main(String[] args){
        /****讀取classpath下的檔案*****/
        //根據本類物件獲取類載入器
        ClassLoader classLoader = new GenerateExcelByTemplate().getClass().getClassLoader();
        //根據檔名從classpath下獲取檔案路徑
        URL pathUrl = classLoader.getResource("excelModel.xml");
        //根據URL路徑獲取檔案物件
        File xmlFile = new File(pathUrl.getFile());
        try {
            //建立Excel
            HSSFWorkbook workbook = new HSSFWorkbook();
            //建立一個sheet頁
            HSSFSheet sheet1 = workbook.createSheet("sheet第一頁");
            /*****通過jdom解析xml檔案,並更具讀取配置生成Excle***/
            //獲取解析器
            SAXBuilder build = new SAXBuilder();
            //將檔案內容讀進解析器,生成document物件
            Document document = build.build(xmlFile);
            //獲取xml跟節點
            Element root = document.getRootElement();
            //獲取excel名稱(跟節點的excelName屬性)
            String excelName = root.getAttribute("excelName").getValue();
            //設定列的屬性和寬度
            Element cloumns = root.getChild("columns");
            //獲取子元素
            List<Element> childCloumns = cloumns.getChildren("cloumn");
            //迴圈設定每個列
            for(int i=0;i<childCloumns.size();i++){
                Element cloumn = childCloumns.get(i);
                //獲取每個列的寬度屬性(width)
                String width = cloumn.getAttribute("width").getValue();
                //擷取,得到單位
                String unit = width.substring(width.length()-2, width.length());
                //將單位清空,得到值
                String num = width.replace(unit, "");
                //根據不同的單位轉換成Excel的寬度
                int excelWitdh = 0;
                switch(unit){
                case "px":
                    excelWitdh = Math.round(Float.parseFloat(num)*37F);
                    break;
                case "em":
                    excelWitdh = Math.round(Float.parseFloat(num)*267.5F);
                    break;
                }
                //設定列寬
                sheet1.setColumnWidth(i, excelWitdh);
            }

            //設定第一行的標題
            Element title = root.getChild("title");
            //標題內容
            String titleStr = title.getText();
            //合併的行數
            int rowspan = title.getAttribute("rowspan").getIntValue()-1;
            //合併的列數
            int colspan = title.getAttribute("colspan").getIntValue()-1;
            //建立0行
            HSSFRow row0 = sheet1.createRow(0);
            //建立一個cell(單元格)
            HSSFCell titleCell = row0.createCell(0);
            //設定內容
            titleCell.setCellValue(titleStr);
            //設定格式
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            //文字居中
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            //設定字型
            HSSFFont cellFont = workbook.createFont();
            //文字顏色
            cellFont.setColor((short) 20);
            //字型加入到樣式中
            cellStyle.setFont(cellFont);
            titleCell.setCellStyle(cellStyle);
            //合併單元格(startY,endY,startX,endX)
            sheet1.addMergedRegion(new CellRangeAddress(0, rowspan, 0, colspan));

            //設定第二行的資料標題
            Element tr = root.getChild("table").getChild("tr");
            List<Element> tds = tr.getChildren("td");
            //建立1行
            HSSFRow row1 = sheet1.createRow(1);
            //設定高度(擷取單位並且轉換長度)
//          row1.setHeight((short) tr.getAttribute("height").getIntValue());
            for(int i=0;i<tds.size();i++){
                Element td = tds.get(i);
                //建立列
                HSSFCell cell1 = row1.createCell(i);
                //設定內容
                cell1.setCellValue(td.getText());
            }
            //設定樣式:迴圈讀取xml配置,就不寫了 TODO

            //生成Excel檔案
            File excelFile = new File("e:/"+excelName+".xls");
            //建立
            excelFile.createNewFile();
            //將Excel內容寫入檔案
            FileOutputStream fos = new FileOutputStream(excelFile);
            //開始寫
            workbook.write(fos);
            //關閉流
            fos.close();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}