刚进公司的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文件的更多相关文章

  1. Java小知识----POI事件模式读取Excel 2007

    一.知识背景 1.读取excel的方法选择问题 java中读excel中的时间,我们通常用POI去解析,在使用new HSSFWorkbook(NEW FileInputStream(excelFil ...

  2. 使用 Apache FOP 2.3 + docbook-xsl-ns-1.79.1 转换 Docbook 5.1 格式的 XML 文档成 PDF/RTF 文件

    使用 Docbook 编写折桂打印平台系统.折桂上传平台系统的产品文档,原因基于如下两点: 第一,文档的不同章节,可使用不同的 .xml 文件,由不同人员分别撰写,图片文件在XML文章中用相对目录方式 ...

  3. C#生成PDF文档,读取TXT文件内容

    using System.IO;using iTextSharp.text;using iTextSharp.text.pdf; //需要在项目里引用ICSharpCode.SharpZipLib.d ...

  4. 【HTML/XML 10】XML文档中的Schema文件

    导读:DTD是对XML文档进行有效性验证的方法之一,事实上,继DTD之后,出现了用来规范和描述XML文档的第二代标准:Schema.Schema是DTD的继承,但是也有其不同的地方,它是真正的以独立的 ...

  5. UINavigationController 导航控制器 ,根据文档写的一些东西

    今天讲了导航控制器UINavigationController 和标签栏视图控制器UITabBarController 先来说一说导航视图控制器  UINavigationController 导航控 ...

  6. 判断pdf、word文档、图片等文件类型(格式)、大小的简便方法

    判断pdf.word文档.图片等文件类型(格式).大小的简便方法 很久没发文了,今天有时间就写一下吧. 关于上传文件,通常我们都需要对其进行判断,限制上传的类型,如果是上传图片,我们甚至会把图片转化成 ...

  7. WPF:将Office文档、任意类型文件嵌入到EXE可执行文件中

    原文:WPF:将Office文档.任意类型文件嵌入到EXE可执行文件中 版权声明:本文为博主原创文章,未经博主允许可以随意转载 https://blog.csdn.net/songqingwei198 ...

  8. 【XML】利用Dom4j读取XML文档以及写入XML文档

    Dom4j简介 dom4j是一个Java的XML API,是jdom的升级品,用来读写XML文件的.dom4j是一个十分优秀的JavaXML API,具有性能优异.功能强大和极其易使用的特点,它的性能 ...

  9. java合并多个word 2007 文档 基于docx4j

    参考文章:http://dh.swzhinan.com/post/185.html 引入的jar包 <dependency> <groupId>org.docx4j</g ...

随机推荐

  1. Android 异步消息处理机制前篇(二):深入理解Message消息池

    版权声明:本文出自汪磊的博客,转载请务必注明出处. 上一篇中共同探讨了ThreadLocal,这篇我们一起看下常提到的Message消息池到底是怎么回事,废话少说吧,进入正题. 对于稍有经验的开发人员 ...

  2. Django框架中的视图和模板

    视图views django中的视图就是用来定义函数来处理一些逻辑的核心地方. django中通过urls来建立路径跟views中的视图函数的映射关系. urls中的映射关系 ''' urlpatte ...

  3. 在O(n)时间复杂度内找到出现超过一半的数

    #include<iostream> using namespace std; bool solver(const int a[],const int n, int & num) ...

  4. 用shape画内圆外方,形成一个圆形头像

    很多人都有过这样的经历,想要在自己写的程序里,上传一张随便大小形状的照片在程序里显示都是圆形照片,或者是方形,或者是三角形,但是写代码又非常麻烦,这里就有一个也可以实现一样效果的方法,那就是用 lay ...

  5. include、include_once、require、require_once其区别

    1.include: 载入文件.未找到文件,则产生E_WARNING 级别的警告错误,脚本继续运行. 2.include_once: 与include 语句作用相同,区别只是如果该文件已经被包含过,则 ...

  6. ibv_get_device_guid()函数

    uint64_t ibv_get_device_guid(struct ibv_device *device); 描述 函数返回RDMA 设备的 GUID(The Global Unique IDen ...

  7. linux shell中单引号、双引号和没有引号的区别

    单引号: 可以说是所见即所得:即将单引号的内的内容原样输出,或者描述为单引号里面看到的是什么就会输出什么. 双引号: 把双引号内的内容输出出来:如果内容中有命令.变量等,会先把变量.命令解析出结果,然 ...

  8. Unity 5--全局光照技术

    本文整理自Unity全球官方网站,原文:UNITY 5 - LIGHTING AND RENDERING 简介全局光照,简称GI,是一个用来模拟光的互动和反弹等复杂行为的算法,要精确的仿真全局光照非常 ...

  9. Windows下docker的安装,将ASP.NET Core程序部署在docker中

    参考文章: https://www.cnblogs.com/jRoger/p/aspnet-core-deploy-to-docker.html https://www.cnblogs.com/jRo ...

  10. HVR又一次load的时候须要将schedule suspend掉

    今天在进行HVR的又一次load的时候.报错了: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fi ...