java代码 把excel转xml
时间: 2023-07-27 07:27:04 浏览: 110
java Excel转化xml
以下是使用Java代码将Excel文件转换为XML文件的示例:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class ExcelToXmlConverter {
public static void main(String[] args) {
try {
// 读取Excel文件
HSSFWorkbook workbook = new HSSFWorkbook(new File("input.xls"));
// 创建XML文档
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// 创建根元素
Element rootElement = doc.createElement("data");
doc.appendChild(rootElement);
// 遍历Excel文件的所有工作表
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
Sheet sheet = workbook.getSheetAt(i);
// 创建工作表元素
Element sheetElement = doc.createElement("sheet");
sheetElement.setAttribute("name", sheet.getSheetName());
rootElement.appendChild(sheetElement);
// 遍历工作表的所有行和列
for (Row row : sheet) {
Element rowElement = doc.createElement("row");
sheetElement.appendChild(rowElement);
for (Cell cell : row) {
Element cellElement = doc.createElement("cell");
cellElement.setAttribute("column", Integer.toString(cell.getColumnIndex() + 1));
rowElement.appendChild(cellElement);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellElement.setTextContent(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
cellElement.setTextContent(Double.toString(cell.getNumericCellValue()));
break;
case Cell.CELL_TYPE_BOOLEAN:
cellElement.setTextContent(Boolean.toString(cell.getBooleanCellValue()));
break;
case Cell.CELL_TYPE_BLANK:
cellElement.setTextContent("");
break;
default:
break;
}
}
}
}
// 将XML文档写入文件
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new FileOutputStream("output.xml"));
transformer.transform(source, result);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上代码使用了Apache POI库来读取Excel文件,使用了Java原生的DOM API来创建XML文档,并使用了Java原生的Transformer API将XML文档写入文件。请根据您的需要进行适当的修改。
阅读全文