基于DOM4j和POI实现的XML文件转换为XLS(即标准EXCEL)的JAVA程序

基于DOM4j和POI实现的XML文件转换为XLS(即标准EXCEL)的JAVA程序

#第一次写博客有点小紧张,希望各位大牛多多包涵

大四狗最近来公司实习,经理大大给了一个测试开发能力的任务,读取xml文件并转换为xls文件,该xml可以通过修改后缀名用xls打开。所以要求即为读取xml格式的文件并且将其内的数据通过xml里的style格式改写成EXCEL标准单元格格式。
注:该程序有部分讨巧,部分公共格式并不是读取出来的而是直接设置好的,如介意请勿取
完整项目链接地址:
https://download.csdn.net/download/amazon_king/10981005

实现过程

首先贴上xml格式的文件:





	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	
	
		
	


	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
			
			
		
		
			
				交易确认表
			
		
		
			
				开始日期:
			
			
				2012-09-10
			
			
				结束日期:
			
			
				2012-09-10
			
			
			
				制表单位:
			
			
				银河证券
			
		
		
			
				父产品名称: 880004_880004
			
		
		
			
				客户名称
			
			
				产品名称
			
			
				证件号码
			
			
				确认日期
			
			
				业务类型
			
			
				申请金额
			
			
				申请份额
			
			
				确认净额
			
			
				确认份额
			
			
				手续费
			
			
				单位净值
			
		
		
			
				test13
			
			
				880004
			
			
				11111111
			
			
				20120910
			
			
				42-强行赎回
			
			
				0
			
			
				985
			
			
				977.12
			
			
				985.00
			
			
				7.88
			
			
				1.0000
			
		
		
			
				test13
			
			
				880004
			
			
				11111111
			
			
				20120910
			
			
				22-申购
			
			
				1000
			
			
				0
			
			
				985
			
			
				985.00
			
			
				15.00
			
			
				1.0000
			
		
		
			
				基金小计
			
			
				1000.0
			
			
				985.0
			
			
				1962.12
			
			
				1970.0
			
			
				22.88
			
			
		
		
			
				*本材料需管理人加盖管理人的印鉴确认方具有效力
			
		
		
			
				**除非管理人提出,否则视为基金管理人对本材料无异议
			
		
		
			
				***请管理人盖章确认后回转一份至[email protected],并可作为向托管人出具汇款指令的附件
			
		
		
			
				****为了不影响客户的资金到账时间及减少与代销机构间的资金交收纠纷,请管理人在确认日的两个工作日内将相应的款项从托管户划至本基金的募集清算账户
			
		
		
			
				*****本管理人已完成本基金所有认购申购客户端确认回访工作,客户认购真实有效!
			
		
		
			
		
		
			
				交易确认表
			
		
		
			
				开始日期:
			
			
				2012-09-10
			
			
				结束日期:
			
			
				2012-09-10
			
			
			
				制表单位:
			
			
				银河证券
			
		
		
			
				父产品名称: 880005_880005
			
		
		
			
				客户名称
			
			
				产品名称
			
			
				证件号码
			
			
				确认日期
			
			
				业务类型
			
			
				申请金额
			
			
				申请份额
			
			
				确认净额
			
			
				确认份额
			
			
				手续费
			
			
				单位净值
			
		
		
			
				test51
			
			
				880005
			
			
				530101198604280050
			
			
				20120910
			
			
				22-申购
			
			
				5000
			
			
				0
			
			
				4950
			
			
				4950.00
			
			
				50.00
			
			
				1.0000
			
		
		
			
				基金小计
			
			
				5000.0
			
			
				0.0
			
			
				4950.0
			
			
				4950.0
			
			
				50.0
			
			
		
		
			
				*本材料需管理人加盖管理人的印鉴确认方具有效力
			
		
		
			
				**除非管理人提出,否则视为基金管理人对本材料无异议
			
		
		
			
				***请管理人盖章确认后回转一份至[email protected],并可作为向托管人出具汇款指令的附件
			
		
		
			
				****为了不影响客户的资金到账时间及减少与代销机构间的资金交收纠纷,请管理人在确认日的两个工作日内将相应的款项从托管户划至本基金的募集清算账户
			
		
		
			
				*****本管理人已完成本基金所有认购申购客户端确认回访工作,客户认购真实有效!
			
		
		
			
		
		
			
				交易确认表
			
		
		
			
				开始日期:
			
			
				2012-09-10
			
			
				结束日期:
			
			
				2012-09-10
			
			
			
				制表单位:
			
			
				银河证券
			
		
		
			
				父产品名称: 880006_880006
			
		
		
			
				客户名称
			
			
				产品名称
			
			
				证件号码
			
			
				确认日期
			
			
				业务类型
			
			
				申请金额
			
			
				申请份额
			
			
				确认净额
			
			
				确认份额
			
			
				手续费
			
			
				单位净值
			
		
		
			
				test31
			
			
				880006
			
			
				111111115
			
			
				20120910
			
			
				24-赎回
			
			
				0
			
			
				985
			
			
				985
			
			
				985.00
			
			
				0.00
			
			
				1.0000
			
		
		
			
				test31
			
			
				880006
			
			
				111111115
			
			
				20120910
			
			
				24-赎回
			
			
				0
			
			
				985
			
			
				985
			
			
				985.00
			
			
				0.00
			
			
				1.0000
			
		
		
			
				基金小计
			
			
				0.0
			
			
				1970.0
			
			
				1970.0
			
			
				1970.0
			
			
				0.0
			
			
		
		
			
				*本材料需管理人加盖管理人的印鉴确认方具有效力
			
		
		
			
				**除非管理人提出,否则视为基金管理人对本材料无异议
			
		
		
			
				***请管理人盖章确认后回转一份至[email protected],并可作为向托管人出具汇款指令的附件
			
		
		
			
				****为了不影响客户的资金到账时间及减少与代销机构间的资金交收纠纷,请管理人在确认日的两个工作日内将相应的款项从托管户划至本基金的募集清算账户
			
		
		
			
				*****本管理人已完成本基金所有认购申购客户端确认回访工作,客户认购真实有效!
			
		
		
			
				操作员:
			
			
				系统管理员
			
			
				
			
			
				1
			
			
				页/共
			
			
				1
			
			
				
			
			
				打印时间:
			
			
				2019年2月18日 下午3:43
			
			
				复核:
			
			
		
	
	
		
			
			
		
		
			9
		
	


刚开始真的一头雾水,没有任何头绪,后来通过查找相关资料以及咨询前辈,终于找到了实现方法

1.首先通过dom4j解析xml文件,将其内的style格式以及table内的相关数据存入实体类中
实体类包括一下三个:
Column(存放列信息)、Style(存放格式信息)、Information(存放table表中的数据信息)
2. 接下来先读取Column类中的column相关样式信息,并且设置列的宽度等数据;
3. 然后读取information类中的数据并且写入Excel中;
4. 接下来读取style类中的样式信息并通过POI写入格式;

接下来是相关代码,一共五个类以及一个xml文件(其中存放相关的包依赖,因为该程序是一个maven项目)

Style类:

package com.jzcf;


import java.util.List;

public class Style {
    private int id;
    private Alignment alignment;
    private List borders;
    private Font  font;
    private Interior interior;
    private NumberFormat numberFormat;

    public Style() {
    }
    public NumberFormat getNumberFormat() {
        return numberFormat;
    }

    public void setNumberFormat(NumberFormat numberFormat) {
        this.numberFormat = numberFormat;
    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Alignment getAlignment() {
        return alignment;
    }

    public void setAlignment(Alignment alignment) {
        this.alignment = alignment;
    }

    public List getBorders() {
        return borders;
    }

    public void setBorders(List borders) {
        this.borders = borders;
    }

    public Font getFont() {
        return font;
    }

    public void setFont(Font font) {
        this.font = font;
    }

    public Interior getInterior() {
        return interior;
    }

    public void setInterior(Interior interior) {
        this.interior = interior;
    }

    public Style(int id, Alignment alignment, List borders, Font font, Interior interior) {
        this.id = id;
        this.alignment = alignment;
        this.borders= borders;
        this.font = font;
        this.interior = interior;
    }

    public Style(int id, NumberFormat numberFormat) {
        this.id = id;
        this.numberFormat = numberFormat;
    }

    public static class Alignment {
        private String horizontal;
        private String vertical;
        private String wrapText;

    public  Alignment(){

    }

        public Alignment(String horizontal, String vertical, String wrapText) {
            this.horizontal = horizontal;
            this.vertical = vertical;
            this.wrapText = wrapText;
        }

        public String getHorizontal() {
            return horizontal;
        }

        public void setHorizontal(String horizontal) {
            this.horizontal = horizontal;
        }

        public String getVertical() {
            return vertical;
        }

        public void setVertical(String vertical) {
            this.vertical = vertical;
        }

        public String getWrapText() {
            return wrapText;
        }

        public void setWrapText(String wrapText) {
            this.wrapText = wrapText;
        }
    }

    public static class Border {
            private String position;
            private String linestyle;
            private int weight;
            private String color;

        public Border() {
        }

        public Border(String position, String linestyle, int weight, String color) {
            this.position = position;
            this.linestyle = linestyle;
            this.weight = weight;
            this.color = color;
        }

        public String getPosition() {
            return position;
        }

        public void setPosition(String position) {
            this.position = position;
        }

        public String getLinestyle() {
            return linestyle;
        }

        public void setLinestyle(String linestyle) {
            this.linestyle = linestyle;
        }

        public int getWeight() {
            return weight;
        }

        public void setWeight(int weight) {
            this.weight = weight;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }
    }

    public static class Font {
            private String fontName;
            private double size;
            private int bold;
            private String color;

        public Font() {
        }

        public Font(String fontName, double size, int bold, String color) {
            this.fontName = fontName;
            this.size = size;
            this.bold = bold;
            this.color = color;
        }

        public String getFontName() {
            return fontName;
        }

        public void setFontName(String fontName) {
            this.fontName = fontName;
        }

        public double getSize() {
            return size;
        }

        public void setSize(double size) {
            this.size = size;
        }

        public int getBold() {
            return bold;
        }

        public void setBold(int bold) {
            this.bold = bold;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }
    }

    public static class Interior {
        private String color;
        private String pattern;

        public Interior() {
        }

        public Interior(String color, String pattern) {
            this.color = color;
            this.pattern = pattern;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }

        public String getPattern() {
            return pattern;
        }

        public void setPattern(String pattern) {
            this.pattern = pattern;
        }
    }

    public static class NumberFormat {
        private String format;

        public NumberFormat() {
        }

        public String getFormat() {
            return format;
        }

        public void setFormat(String format) {
            this.format = format;
        }

        public NumberFormat(String format) {
            this.format = format;
        }
    }
}

Column类:

package com.jzcf;

public class Column {
    private double width;
    private int autofitwidth=0;

    public Column() {
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public Column(double width, int autofitwidth) {
        this.width = width;
        this.autofitwidth = autofitwidth;
    }
}

Information类:

package com.jzcf;

import java.util.List;

public class Information {
    private String name;
   private List row;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Information() {
    }

    public List getRow() {
        return row;
    }

    public void setRow(List row) {
        this.row = row;
    }

    public Information(String name, List row) {
        this.name = name;
        this.row = row;
    }

    public static class Row {
        private int autofitheight;
        private double height;
        private List  cell;

        public Row() {
        }

        public Row(int autofitheight, double height, List cell) {
            this.autofitheight = autofitheight;
            this.height = height;
            this.cell = cell;
        }

        public int getAutofitheight() {
            return autofitheight;
        }

        public void setAutofitheight(int autofitheight) {
            this.autofitheight = autofitheight;
        }

        public double getHeight() {
            return height;
        }

        public void setHeight(double height) {
            this.height = height;
        }

        public List getCell() {
            return cell;
        }

        public void setCell(List cell) {
            this.cell = cell;
        }

        public static class Cell {
            private int index;
            private int styleID;
            private int MergeAcross;
            private int MergeDown;
            private Data data;

            public Cell() {
            }

            public Cell(int index, int styleID, int mergeAcross, int mergeDown, Data data) {
                this.index = index;
                this.styleID = styleID;
                MergeAcross = mergeAcross;
                MergeDown = mergeDown;
                this.data = data;
            }

            public int getIndex() {
                return index;
            }

            public void setIndex(int index) {
                this.index = index;
            }

            public int getStyleID() {
                return styleID;
            }

            public void setStyleID(int styleID) {
                this.styleID = styleID;
            }

            public int getMergeAcross() {
                return MergeAcross;
            }

            public void setMergeAcross(int mergeAcross) {
                MergeAcross = mergeAcross;
            }

            public int getMergeDown() {
                return MergeDown;
            }

            public void setMergeDown(int mergeDown) {
                MergeDown = mergeDown;
            }

            public Data getData() {
                return data;
            }

            public void setData(Data data) {
                this.data = data;
            }

            public static class Data {
                private int ticked;
                private String type;
                private String dat;//用于存放字段数据

                public int getTicked() {
                    return ticked;
                }

                public void setTicked(int ticked) {
                    this.ticked = ticked;
                }

                public String getType() {
                    return type;
                }

                public void setType(String type) {
                    this.type = type;
                }

                public String getDat() {
                    return dat;
                }

                public void setDat(String dat) {
                    this.dat = dat;
                }

                public Data() {
                }

                public Data(int ticked, String type, String dat) {
                    this.ticked = ticked;
                    this.type = type;
                    this.dat = dat;
                }
            }
        }
    }
}

XmlReader类(用于解析xml文件):

package com.jzcf;



import java.util.*;

import org.dom4j.Document;
import org.dom4j.DocumentException;

import org.dom4j.Element;


import java.util.List;

public class XmlReader {
    public static Map  getStyle(Document document) {//获取样式
        Map styleMap = new LinkedHashMap();//创建一个LinkedHashMap用于存放style,按照id查找
        Style style = null; //新建一个Style类用于存放节点数据

        Style.NumberFormat numberFormat = new Style.NumberFormat();

        Element root = document.getRootElement();//获取根节点
        Element styles = root.element("Styles");//获取根节点下的Styles节点
        List lstyle = styles.elements("Style");//获取Styles下的Style节点
        Iterator it = lstyle.iterator();
        Element e = (Element) it.next();
        while (it.hasNext()) {
            style = new Style();//新建一个Style类用于存放节点数据
            e = (Element) it.next();
            int id = Integer.parseInt(e.attributeValue("ID"));
            style.setId(id);//设置style的id
            if (id == 1) {//当id为1时,设置为另一中构造方法
               /* Element enumberFormat = e.element("NumberFormat");//获取Style下的NumberFormat节点
                numberFormat.setFormat(enumberFormat.attributeValue("Format"));
                style.setNumberFormat(numberFormat);*/
                continue;
            }
            Style.Alignment alignment = new Style.Alignment();
            Element ealignment = e.element("Alignment");//获取Style下的Alignment节点
            //设置aligment的相关属性,并且设置style的aliment属性
            alignment.setHorizontal(ealignment.attributeValue("Horizontal"));
            alignment.setVertical(ealignment.attributeValue("Vertical"));
            alignment.setWrapText(ealignment.attributeValue("WrapText"));
            style.setAlignment(alignment);

            Element Borders = e.element("Borders");//获取Style下的Borders节点
            List Border = Borders.elements("Border");//获取Borders下的Border节点
            Iterator bdIt = Border.iterator();//用迭代器遍历Border节点
            //利用List来存取borders下的多个border并放入style

            List lborders = new ArrayList();
            while (bdIt.hasNext()) {
                Element bd = (Element) bdIt.next();
                Style.Border border = new Style.Border();
                border.setPosition(bd.attributeValue("Position"));
                if (bd.attribute("LineStyle") != null) {
                    border.setLinestyle(bd.attributeValue("LineStyle"));
                    int weight = Integer.parseInt(bd.attributeValue("Weight"));
                    border.setWeight(weight);
                    border.setColor(bd.attributeValue("Color"));
                }
                lborders.add(border);
            }
            style.setBorders(lborders);
            for (int i = 0; i < style.getBorders().size(); i++) {
                // System.out.println(style.getBorders().get(i).getPosition());
            }

            //设置font的相关属性,并且设置style的font属性
            Style.Font font = new Style.Font();
            Element efont = e.element("Font");
            font.setFontName(efont.attributeValue("FontName"));
            double size = Double.parseDouble(efont.attributeValue("Size"));
            font.setSize(size);
            if (efont.attribute("Bold") != null) {
                int bold = Integer.parseInt(efont.attributeValue("Bold"));
                font.setBold(bold);
            }
            font.setColor(efont.attributeValue("Color"));
            style.setFont(font);
            //设置Interior的相关属性,并且设置style的interior属性
            Style.Interior interior = new Style.Interior();
            if (e.element("Interior") != null) {
                Element einterior = e.element("Interior");
                interior.setColor(einterior.attributeValue("Color"));
                interior.setPattern(einterior.attributeValue("Pattern"));
            }
            style.setInterior(interior);
            if (e.element("NumberFormat") != null) {
                //设置NumberFormat的相关属性,并且设置style的NumberFormat属性
                Element enumberFormat = e.element("NumberFormat");//获取Style下的Alignment节点
                numberFormat.setFormat(enumberFormat.attributeValue("Format"));
                style.setNumberFormat(numberFormat);
            }
            styleMap.put(id, style);

        }

        Element Names = root.element("Names");//获取根节点下的Names节点
        Element NamedRange = Names.element("NamedRange");//获取根节点下的NamedRange节点
        String name = NamedRange.attributeValue("Name");//获取ss:Name
        String namedRange = NamedRange.attributeValue("RefersTo");//获取ss:RefersTo
        return styleMap;
    }
public  static  List  getColumn(Document document){
    Element root = document.getRootElement();
    Element worksheet = root.element("Worksheet");//读取根节点下的Worksheet节点
    String name = worksheet.attributeValue("Name");
    Element table = worksheet.element("Table");//读取Worksheet下的ss:Table节点
    List column = table.elements("Column");//读取ss:Table下的所有ss:Column节点
    List columns = new ArrayList();
    for (Iterator it = column.iterator(); it.hasNext(); ) {
        Column column1 = new Column();//通过创建column来存取column里的值
        Element eColumn = (Element) it.next();
        double width = Double.parseDouble(eColumn.attributeValue("Width"));
        column1.setWidth(width);
        columns.add(column1);
    }
   return columns;
}
    public static Information getData(Document document) {//获取具体数据
        Element root = document.getRootElement();
        Element worksheet = root.element("Worksheet");//读取根节点下的Worksheet节点
        Element table = worksheet.element("Table");//读取Worksheet下的ss:Table节点

        Information information = new Information();
        information.setName(worksheet.attributeValue("Name"));
        List row = table.elements("Row");//读取Worksheet下的Row节点
        List lrow = new ArrayList();
        for (Iterator it = row.iterator(); it.hasNext(); ) {
            //设置row对象属性并存放入list,存入information
            Information.Row row1 = new Information.Row();
            Element eRow = (Element) it.next();
            int autofitheight = Integer.parseInt(eRow.attributeValue("AutoFitHeight"));
            row1.setAutofitheight(autofitheight);
            if (eRow.attributeValue("Height")!= null) {
                double height = Double.parseDouble(eRow.attributeValue("Height"));
                row1.setHeight(height);
            }
            lrow.add(row1);//将一个个row对象存放入list lrow中
            List lcell = new ArrayList();//list用于存放cell
            List cell = eRow.elements("Cell");//读取Row下的Cell节点
            for (Iterator it1 = cell.iterator(); it1.hasNext(); ) {
                Element eCell = (Element) it1.next();
                //将cell节点相关数据存入row
                Information.Row.Cell cell1 = new Information.Row.Cell();
                int index = Integer.parseInt(eCell.attributeValue("Index"));
                cell1.setIndex(index);
                int styleid = Integer.parseInt(eCell.attributeValue("StyleID"));
                cell1.setStyleID(styleid);
                if (eCell.attributeValue("MergeAcross") != null) {
                    int mergeacross = Integer.parseInt(eCell.attributeValue("MergeAcross"));
                    cell1.setMergeAcross(mergeacross);
                }
                if (eCell.attributeValue("MergeDown") != null) {
                    int mergedown = Integer.parseInt(eCell.attributeValue("MergeDown"));
                    cell1.setMergeDown(mergedown);
                }
                lcell.add(cell1);//将一个个cell添加入listlcell中
                if(eCell.element("Data")!=null) {
                    Element data = eCell.element("Data");//读取Cell下的Data节点
                    //将data节点相关数据存入cell1
                    Information.Row.Cell.Data data1 = new Information.Row.Cell.Data();
                if (data.attributeValue("Ticked")!= null) {
                    int ticked = Integer.parseInt(data.attributeValue("Ticked"));
                    data1.setTicked(ticked);
                }
                    data1.setType(data.attributeValue("Type"));
                    data1.setDat(data.getText());
                    cell1.setData(data1);
                }
            }
            row1.setCell(lcell);
        }
        information.setRow(lrow);//将lrow这个list存放为information的row属性中
return information;
    }
}

ExcelAnalysis类(用于写入excle文件):

package com.jzcf;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.util.*;


import java.util.List;
import java.util.ArrayList;

import org.apache.poi.ss.usermodel.IndexedColors;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;

public class ExcelAnalysis {
    /**
     * 注意:同一行上的只能创建同一个行对象row  否则赋值的内容会被覆盖。
     */
    public static void main(String[] args) throws DocumentException {
        File inputFile = new File("D:\\Work\\a.xml");
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputFile);
        List columnList = XmlReader.getColumn(document);//读取列的相关信息
        Map styleMap = XmlReader.getStyle(document);//读取style相关信息
        Information information = XmlReader.getData(document);
        //1.创建一个webbook,对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //2.在建立的工作簿中添加一个sheet,对应Excell文件中的工作簿,并设置工作簿名称
        HSSFSheet sheet = wb.createSheet(information.getName());

        for (int i = 0; i < columnList.size(); i++) {//读取column对象里的值设置列宽
            sheet.setColumnWidth(i, (int) columnList.get(i).getWidth() * 42);
        }
        //读取information下的row节点设置行高为自动调整
        HSSFRow row = sheet.createRow(0);
        row.setHeight((short) 380);//目的是想把行高设置成31px
        int rownum = information.getRow().size();//行的总数
        CellRangeAddress region1 = new CellRangeAddress(0, 0, (short) 0, (short) 20);//合并单元格
        CellRangeAddress region2 = new CellRangeAddress(0, 37, (short) 21, (short) 21);//合并单元格
        sheet.addMergedRegion(region1);
        sheet.addMergedRegion(region2);
        for (int i = 1; i < rownum; i++) {
            Row row1 = sheet.createRow(i);
            if (i == 1 || i == 14 || i == 26) {
                row1.setHeight((short) 480);
            }
            //建立单元格
            int cellnum = information.getRow().get(i).getCell().size();//每一行单元格的总数
            List lindex = new ArrayList();
            for (int j = 0; j < cellnum; j++) {//将索引index放入一个list中
                int index = information.getRow().get(i).getCell().get(j).getIndex();//获取该单元格起始列数
                lindex.add(index);
            }
            for (int j = 0; j < cellnum; j++) {

                int index = information.getRow().get(i).getCell().get(j).getIndex();//获取该单元格起始列数
                int mergeAcross = index - 1;
                if (information.getRow().get(i).getCell().get(j).getMergeAcross() != 0) {
                    mergeAcross += information.getRow().get(i).getCell().get(j).getMergeAcross();//获取该单元格结束列数
                    CellRangeAddress r1 = new CellRangeAddress(i, i, (short) index - 1, (short) mergeAcross);//合并单元格
                    sheet.addMergedRegion(r1);
                }
                if (information.getRow().get(i).getCell().get(j).getData() != null) {//设置数据相关的格式
                    HSSFCell cell = sheet.getRow(i).createCell(lindex.get(j) - 1);
                    String data = information.getRow().get(i).getCell().get(j).getData().getDat();//获取相应序列的data
                    cell.setCellValue(data);
                    int styleID = information.getRow().get(i).getCell().get(j).getStyleID();//获取每一个单元格相应的styleid
                    Set> entrySet = styleMap.entrySet();
                    //遍历Set集合
                    Iterator> it1 = entrySet.iterator();
                    while (it1.hasNext()) {
                        //得到每一对对应关系
                        Map.Entry entry = it1.next();
                        //通过每一对对应关系获取对应的key
                        int key = entry.getKey();
                        if (styleID == key) {
                            //通过每一对对应关系获取对应的value
                            HSSFFont font = wb.createFont();
                            Style value = entry.getValue();
                            HSSFCellStyle style = wb.createCellStyle();
                            //首先设置共有的属性部分
                            style.setVerticalAlignment(VerticalAlignment.TOP);
                            style.setWrapText(true);
                            String horizontal = value.getAlignment().getHorizontal();
                            if (horizontal.equals("Left")) {
                                style.setAlignment(HorizontalAlignment.LEFT);
                            } else if (horizontal.equals("Center")) {
                                style.setAlignment(HorizontalAlignment.CENTER);
                            } else {
                                style.setAlignment(HorizontalAlignment.RIGHT);
                            }
                            for (int k = 0; k < value.getBorders().size(); k++) {//设置边框样式
                                if (value.getBorders().get(k).getLinestyle() != null) {
                                    if (k == 0) {
                                        style.setBorderBottom(BorderStyle.THIN);
                                    } else if (k == 1) {
                                        style.setBorderTop(BorderStyle.THIN);
                                    } else if (k == 2) {

                                        style.setBorderLeft(BorderStyle.THIN);

                                    } else if (k == 3) {
                                        style.setBorderRight(BorderStyle.THIN);
                                        if (information.getRow().get(i).getCell().get(j).getMergeAcross() != 0) {
                                            mergeAcross = information.getRow().get(i).getCell().get(j).getMergeAcross() + index - 1;//获取该单元格结束列数
                                            CellRangeAddress r1 = new CellRangeAddress(i, i, (short) index - 1, (short) mergeAcross);//
                                            RegionUtil.setBorderTop(BorderStyle.THIN, r1, sheet);
                                            RegionUtil.setBorderBottom(BorderStyle.THIN, r1, sheet);
                                            RegionUtil.setBorderLeft(BorderStyle.THIN, r1, sheet);
                                            RegionUtil.setBorderRight(BorderStyle.THIN, r1, sheet);
                                        }
                                    }
                                }
                            }
                            cell.setCellStyle(style);
                            if (value.getInterior().getPattern() != null) {
                                style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());  //填充单元格
                                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                            }
                            font.setFontName("serif");//设置字体
                            if (value.getFont().getSize() == 16) {
                                font.setFontHeightInPoints((short) 16);//设置字号
                            } else {
                                font.setFontHeightInPoints((short) 10);//设置字号
                            }
                            if (value.getFont().getBold() == 1) {
                                font.setBold(true);
                            }
                            font.setColor(IndexedColors.BLACK.getIndex());
                            style.setFont(font);
                        }

                    }
                }
            }

        }

        FileOutputStream fileOut;
        try {
            fileOut = new FileOutputStream("D:/Work/c.xls");
            wb.write(fileOut);
            fileOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("写出成功!");
    }
}

包依赖:




  4.0.0

  com.jzcf
  xmlwork
  1.0-SNAPSHOT

  xmlwork
  
  http://www.example.com

  
    UTF-8
    1.7
    1.7
      1.2.71
  

  
    
      xml-apis
      xml-apis
      1.3.02
    
    
      xerces
      xercesImpl
      2.6.2-jaxb-1.0.6
    

    
      dom4j
      dom4j
      1.5
    

    
      jaxen
      jaxen
      1.1
    
    
      junit
      junit
      4.11
      test
    
    
      org.apache.poi
      poi-ooxml
      3.17
    
    
      org.apache.poi
      poi
      3.17
    
    
      org.apache.poi
      poi-examples
      3.17
    
    
      org.apache.poi
      poi-excelant
      3.17
    
    
      org.apache.poi
      poi-ooxml-schemas
      3.17
    
    
      org.apache.poi
      poi-scratchpad
      3.17
    
    
      dom4j
      dom4j
      1.6.1
    
    
      stax
      stax-api
      1.0
    
    
      org.apache.xmlbeans
      xmlbeans
      2.6.0
    
    
      org.apache.poi
      poi
      3.17
    

    
      commons-io
      commons-io
      2.0
    
      
          org.jetbrains.kotlin
          kotlin-stdlib-jdk8
          ${kotlin.version}
      
      
          org.jetbrains.kotlin
          kotlin-test
          ${kotlin.version}
          test
      

  

  
    
      
        
        
          maven-clean-plugin
          3.1.0
        
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.8.0
        
        
          maven-surefire-plugin
          2.22.1
        
        
          maven-jar-plugin
          3.0.2
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
        
        
          maven-site-plugin
          3.7.1
        
        
          maven-project-info-reports-plugin
          3.0.0
        
      
    
      
          
              org.jetbrains.kotlin
              kotlin-maven-plugin
              ${kotlin.version}
              
                  
                      compile
                      compile
                      
                          compile
                      
                  
                  
                      test-compile
                      test-compile
                      
                          test-compile
                      
                  
              
              
                  1.8
              
          
          
              org.apache.maven.plugins
              maven-compiler-plugin
              
                  
                      compile
                      compile
                      
                          compile
                      
                  
                  
                      testCompile
                      test-compile
                      
                          testCompile
                      
                  
              
          
      
  


以上就是我本次程序的实现过程及代码,后续会放一个打包好的项目文件,有需要的朋友可以自取

你可能感兴趣的:(JAVA,POI,DOM4J,JAVA,XML,XLS)