基于POI和DOM4将Excel(2007)文档写进Xml文件
刚进公司的training, 下面是要求:
Requirements
- Write a java program to read system.xlsx
- Use POI API to parse all contents in the excel
- Write all contents to an output file
- The file should in XML format(optional)
- The program can start with a bat command(optional)

Reference
- POI official site -- http://poi.apache.org/ ---下载poi相关的包
- CBX-Builder implementation -- \\triangle\share\git\training\CBX_Builder [develop branch]
package polproject; import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter; public class ExcelToXml { /**
* @param args
*/
public static void main(String[] args) throws Exception { toXml("D:/excel/system.xlsx", "D:/excel/system.xml");
} /**
* excel to xml
*/
public static void toXml(String sourcePath, String targetPath) throws Exception { // 输出格式化
final OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8"); // 指定XML编码
final XMLWriter output = new XMLWriter(new FileWriter(targetPath), format); // 使用DocumentHelper.createDocument方法建立一个文档实例
final Document document = DocumentHelper.createDocument();
Element rootElm = document.getRootElement(); final File file = new File(sourcePath);
final String fileName = file.getName(); // 如果想获得不带点的后缀,变为fileName.lastIndexOf(".")+1
final String prefix = fileName.substring(fileName.lastIndexOf(".")); // 得到后缀名长度
final int prefix_num = prefix.length(); // 得到文件名。去掉了后缀
final String fileOtherName = fileName.substring(0, fileName.length() - prefix_num); if (rootElm == null) {
// 创建根节点
rootElm = document.addElement(fileOtherName);
rootElm.addAttribute("pistion", fileName);
}
final Workbook wb = WorkbookFactory.create(new File(sourcePath));
final int sheetNum = wb.getNumberOfSheets();
for (int i = 0; i < sheetNum; i++) {
final Sheet sheet = wb.getSheetAt(i); // 标记是否接下来的是否为fieldIdLabel
boolean isFieldIdLabel = false;
boolean isFieldValue = false;
int coloumNum = 0;
final List<String> fields = new ArrayList<String>();
final String sheetName = sheet.getSheetName(); // 1#添加一级节点
final Element firstElm = rootElm.addElement("sheet");
firstElm.addAttribute("id",sheetName);
firstElm.addAttribute("position",fileName+ "," +sheetName);
Element secondElm = null;
Element thirdElm = null;
for (final Row row : sheet) {
coloumNum = row.getPhysicalNumberOfCells(); Element fourthElm = null;
boolean isNextRow = true;
for (final Cell cell : row) { final String cellStr = cellValueToString(cell); // 2#添加二级节点
if (cellStr.startsWith("##")) {
final String cellElm = cellStr.substring(2);
secondElm = firstElm.addElement(cellElm);
secondElm.addAttribute("position", fileName + "," + sheetName +"," +String.valueOf(row.getRowNum()+1)); // 3#添加三级节点
} else if (cellStr.startsWith("#begin")) {
thirdElm = secondElm.addElement("elements");
final String[] arrayStr = cellStr.split(":");
if (arrayStr.length == 1) {
thirdElm.addAttribute("id", "default");
isFieldIdLabel = true;
} else {
thirdElm.addAttribute("pistion", arrayStr[1]);
isFieldIdLabel = true;
} // 4#收集添加四级节点
} else if (isFieldIdLabel) {
//如果不为空,则列数-1,并把头部加进fields里
if( !cellStr.isEmpty()){
if (coloumNum != 0) {
fields.add(cellStr);
coloumNum=coloumNum-1;
}
if (coloumNum == 0) {
isFieldIdLabel = false;
isFieldValue = true;
}
}else{//如果为空,则列数就只-1
if (coloumNum != 0) {
coloumNum=coloumNum-1;
}
if (coloumNum == 0) {
isFieldIdLabel = false;
isFieldValue = true;
}
} } else if (cellStr.startsWith("#end")) {
isFieldValue = false;
fields.clear();
// 5#写入filedvalue
} else if (isFieldValue) { if (isNextRow) {
fourthElm = thirdElm.addElement("element");
fourthElm.addAttribute("position", fileName + "," +sheetName +"," +String.valueOf(row.getRowNum()+1));
final int celIndex = cell.getColumnIndex();
Element fifthElm=null;
if(fields.get(celIndex).lastIndexOf("*")>0){
fifthElm = fourthElm.addElement(fields.get(celIndex).substring(0,fields.get(celIndex).indexOf("*")));
}else{
fifthElm = fourthElm.addElement(fields.get(celIndex));
} fifthElm.setText(cellStr);
isNextRow = false;
} else {
final int celIndex = cell.getColumnIndex();
Element fifthElm=null;
if (celIndex < fields.size()) {
if(fields.get(celIndex).lastIndexOf("*")>0){
fifthElm = fourthElm.addElement(fields.get(celIndex).substring(0,fields.get(celIndex).indexOf("*")-1));
}else{
fifthElm = fourthElm.addElement(fields.get(celIndex));
}
fifthElm.setText(cellStr);
}
}
} else {
// System.out.println(coloumNum + " " + isFieldIdLabel);
}
}
}
}
System.out.println("end---------------------");
output.write(document);
output.flush();
output.close();
} /**
* 将单元格的内容全部转换成字符串
*/
private static String cellValueToString(Cell cell) {
String str = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
str = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
str = cell.getDateCellValue().toString();
} else {
str = String.valueOf(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
str = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
str = cell.getCellFormula();
break;
default:
// System.out.println("can not format cell value :" + cell.getRichStringCellValue());
str = cell.getRichStringCellValue().getString();
break;
}
return str;
}
}
结果图:
基于POI和DOM4将Excel(2007)文档写进Xml文件的更多相关文章
- Java小知识----POI事件模式读取Excel 2007
一.知识背景 1.读取excel的方法选择问题 java中读excel中的时间,我们通常用POI去解析,在使用new HSSFWorkbook(NEW FileInputStream(excelFil ...
- 使用 Apache FOP 2.3 + docbook-xsl-ns-1.79.1 转换 Docbook 5.1 格式的 XML 文档成 PDF/RTF 文件
使用 Docbook 编写折桂打印平台系统.折桂上传平台系统的产品文档,原因基于如下两点: 第一,文档的不同章节,可使用不同的 .xml 文件,由不同人员分别撰写,图片文件在XML文章中用相对目录方式 ...
- C#生成PDF文档,读取TXT文件内容
using System.IO;using iTextSharp.text;using iTextSharp.text.pdf; //需要在项目里引用ICSharpCode.SharpZipLib.d ...
- 【HTML/XML 10】XML文档中的Schema文件
导读:DTD是对XML文档进行有效性验证的方法之一,事实上,继DTD之后,出现了用来规范和描述XML文档的第二代标准:Schema.Schema是DTD的继承,但是也有其不同的地方,它是真正的以独立的 ...
- UINavigationController 导航控制器 ,根据文档写的一些东西
今天讲了导航控制器UINavigationController 和标签栏视图控制器UITabBarController 先来说一说导航视图控制器 UINavigationController 导航控 ...
- 判断pdf、word文档、图片等文件类型(格式)、大小的简便方法
判断pdf.word文档.图片等文件类型(格式).大小的简便方法 很久没发文了,今天有时间就写一下吧. 关于上传文件,通常我们都需要对其进行判断,限制上传的类型,如果是上传图片,我们甚至会把图片转化成 ...
- WPF:将Office文档、任意类型文件嵌入到EXE可执行文件中
原文:WPF:将Office文档.任意类型文件嵌入到EXE可执行文件中 版权声明:本文为博主原创文章,未经博主允许可以随意转载 https://blog.csdn.net/songqingwei198 ...
- 【XML】利用Dom4j读取XML文档以及写入XML文档
Dom4j简介 dom4j是一个Java的XML API,是jdom的升级品,用来读写XML文件的.dom4j是一个十分优秀的JavaXML API,具有性能优异.功能强大和极其易使用的特点,它的性能 ...
- java合并多个word 2007 文档 基于docx4j
参考文章:http://dh.swzhinan.com/post/185.html 引入的jar包 <dependency> <groupId>org.docx4j</g ...
随机推荐
- Numpy数组的基本运算操作
一.算术运算符 In [3]: a = np.arange(0,5) Out[3]array([0, 1, 2, 3, 4]) In [4]: a+4 Out[4]: array([4, 5, 6, ...
- 可靠的、可扩展的、可维护的数据系统 ------《Designing Data-Intensive Applications》读书笔记1
坦白说也是机缘巧合,在硕士生阶段进入分布式系统领域学习.无论是大规模存储或计算,其核心也是运用分布式技术利用并行性来解决数据密集型应用的需求.最近开始在啃这本<Designing Data-In ...
- js实现关键词高亮显示 正则匹配
html 和ajax 部分就不写了,只需将需要匹配的文字传进去就可以了 比如匹配后台传回的字符串data.content中的关键词:直接调用: data.content = highLightKeyw ...
- ChatterBot之快速入门01
本人运行环境为Python 3.5.2; 首先你需要导入chatterbot 的包,如果没有你先需要下载 使用命令 pip install chatterbot 1 # -*- coding: utf ...
- 51Nod 1007 正整数分组 01背包
将一堆正整数分为2组,要求2组的和相差最小.例如:1 2 3 4 5,将1 2 4分为1组,3 5分为1组,两组和相差1,是所有方案中相差最少的.Input第1行:一个数N,N为正整数的数量.第2 - ...
- nefu 115 循环节
斐波那契的整除 Problem:115 Time Limit:1000ms Memory Limit:65536K Description 已知斐波那契数列有如下递归定义,f(1)=1,f(2)=1, ...
- eclipse中将本地项目上传到svn库
转载文章:http://blog.csdn.net/singit/article/details/48972197
- rabbitmq(中间消息代理)在python中的使用
在之前的有关线程,进程的博客中,我们介绍了它们各自在同一个程序中的通信方法.但是不同程序,甚至不同编程语言所写的应用软件之间的通信,以前所介绍的线程.进程队列便不再适用了:此种情况便只能使用socke ...
- 【NOIP2014提高组】飞扬的小鸟
https://www.luogu.org/problem/show?pid=1941 从某一点开始飞直到飞出地图最少点击屏幕的次数,显然只和该点的坐标唯一相关,没有后效性,考虑用DP解.令f(i,j ...
- 【机器学习】RNN学习
感谢中国人民大学的胡鹤老师,课程容量巨大,收获颇丰. 之前提到的CNN模型主要用到人类的视觉中枢,但其有一劣势,无论是人类的视觉神经还是听觉神经,所接受到的都是一个连续的序列,使用CNN相当于割裂了前 ...