excel转xml文件其实是很简单的,主要在于你要知道怎么去解决这个业务上的流程,那我们应该知道一点的是:我们必须把数据先从excel中读出来,然后对这些数据进行xml格式的封装。这样我们就很容易解决这个问题,那么还有个问题就是我们需要如何去解决呢?
首先我们应该知道这两个流程如何去实现。第一步:如何从excel中读取当中的数据,我这里所要用的jar包是jxl.jar。第二就是用jdom.jar来对数据进行xml格式的转换。
这样,我们的基本步骤也就了解了,那么现在我们就可以自己用代码去实现了。代码如下:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//这里是生成工作簿
Workbook wb = null;
//path.put("pt", "c:/excel.xls");
// 创建根节点;
Element root = new Element("sheet");
// 将根节点添加到文档中;
Document Doc = new Document(root);
InputStream instream = new FileInputStream(“c:excel.xml”);
try {
readwb = Workbook.getWorkbook(instream);
// 获取第一张Sheet表
Sheet sheet = wb.getSheet(0);
// 获取Sheet表中所包含的总列数
int columns = sheet.getColumns();
// 获取Sheet表中所包含的总行数
int rows = sheet.getRows();
// 获取指定单元格的对象引用
for (int i = 0; i < rows; i++) {
Element elements = new Element("tr");
for (int j = 0; j < columns; j++) {
Cell cell = sheet.getCell(j, i);
// str[i][j]=cell.getContents();//在此创建一个二维数组,获取单元格的数据
// 生成xml文件
elements.addContent(new Element("cell").setText(cell
.getContents())); // 填写单元格的数据。
root.addContent(elements.detach());
}
}
Format format = Format.getPrettyFormat();
XMLOutputter XMLOut = new XMLOutputter(format);
XMLOut.output(Doc, new FileOutputStream("C:/Users/cyl/Desktop/books.xml"));
} catch (BiffException e) {
e.printStackTrace();
}
}
如有疑问,请加qq974077198