如何使用DOM解析器和Apache POI将XLSX解析为XML时附加SharedStringsTable

时间:2015-05-20 12:12:19

标签: java excel parsing dom apache-poi

我的代码是这样的:

public class ReadXlsx {
public static void processDoc(String path)throws Exception
{
    OPCPackage pkg = OPCPackage.open(path); 
    XSSFReader r = new XSSFReader( pkg ); 
    SharedStringsTable sst = r.getSharedStringsTable();       
    DOMParser parser = new DOMParser(); 
    InputStream inp = r.getSheet("rId1"); 
    InputSource inpSource = new InputSource(inp); 
    inpSource.setEncoding("UTF-8");
    parser.parse(inpSource);


    Document doc = parser.getDocument(); 
    inp.close(); 

    OutputStream writer = new FileOutputStream(System.getProperty("user.home") + "//Desktop"+"//file.xml"); 
    TransformerFactory transfac = TransformerFactory.newInstance(); 
    Transformer trans = transfac.newTransformer(); 
                            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 
    trans.setOutputProperty(OutputKeys.INDENT, "yes"); 
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 

    //create string from xml tree 

    StreamResult result = new StreamResult(writer); 
    DOMSource source = new DOMSource(doc); 
    trans.transform(source, result); 
    XmlToJson.Convert(System.getProperty("user.home") + "\\Desktop"+"\\file.xml",System.getProperty("user.home") + "\\Desktop"+"\\Json4.json");
}}

问题是,当我将.xlsx文件转换为.xml文件时,工作表中的每个字符串都将转换为类似的内容

<c r="A1" s="43" t="s"><v>93</v></c>

这意味着A1中的字符串是sharedStrings.xml中的第94个字符串 (t = s v = 93表示单元格是一个字符串数组值为93)

我可以获取SharedStringsTable,但我不知道如何将其包含在 XML文件因此它将显示字符串而不是t = s v = 93 like

<c r="A1" s="43"><t>This is String.</t></c>

感谢。

1 个答案:

答案 0 :(得分:0)

您需要使用SharedStringsTable对象中的getEntryAt(int)函数,如下所示:

 SharedStringsTable sst = r1.getSharedStringsTable();//r1 being your XSSFReader
 CTRst st = sst.getEntryAt(k);//k is the index that you have in <v> tag
 st.getT();//getT() gets your value

其类中的SharedStringsTable维护为ArrayList和HashMap,它们都是私有类成员。我写的上面的代码片段是从ArrayList成员访问它。当您创建SharedStringsTable对象时,整个SharedStrings xml分别作为HashMap和ArrayList加载。因此,流式xlsx文件确实具有此限制。如果有解决方法,我想知道因为我们无法覆盖SharedStringsTable类的私有成员(HashMap和ArrayList)。