XLSTransformer
是 Apache POI 庫中的一個類,用于將 XML 文檔轉換為 Excel 工作表。以下是一個簡單的示例,演示如何使用 XLSTransformer
將 XML 數據轉換為 Excel 文件:
pom.xml
文件中添加以下依賴:<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
data.xml
:<?xml version="1.0" encoding="UTF-8"?>
<data>
<row>
<cell>Name</cell>
<cell>Age</cell>
</row>
<row>
<cell>John Doe</cell>
<cell>30</cell>
</row>
<row>
<cell>Jane Smith</cell>
<cell>28</cell>
</row>
</data>
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class XLSTransformerExample {
public static void main(String[] args) throws IOException {
FileInputStream xmlFile = new FileInputStream("data.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
NodeList rowList = doc.getElementsByTagName("row");
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("XML to Excel");
for (int i = 0; i < rowList.getLength(); i++) {
Node rowNode = rowList.item(i);
Row row = sheet.createRow(i);
NodeList cellList = rowNode.getChildNodes();
for (int j = 0; j < cellList.getLength(); j++) {
Node cellNode = cellList.item(j);
Cell cell = row.createCell(j);
if (cellNode.getNodeType() == Node.ELEMENT_NODE) {
String cellValue = cellNode.getTextContent();
cell.setCellValue(cellValue);
}
}
}
FileOutputStream fileOut = new FileOutputStream("output.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
xmlFile.close();
System.out.println("Excel file with XML data has been generated!");
}
}
運行此代碼后,將在當前目錄下生成一個名為 output.xlsx
的 Excel 文件,其中包含從 XML 文件中提取的數據。注意,這個示例僅適用于簡單的 XML 數據,對于更復雜的數據結構,您可能需要對代碼進行相應的調整。