为了账号安全,请及时绑定邮箱和手机立即绑定

Java读取XML与xls文件

标签:
Java

前言

有时候需要通过编程来读取一些xls文件的内容,或者xml文件,读取这两种类型的文件,没什么关联,只是碰巧需要同时读取两种类型的文件。

准备

读取xls文件,可以使用Apache的一个开源项目.POI,有兴趣的自己看一下官方介绍.

使用Maven集成

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.14</version></dependency>

读取xml文件,使用系统自带的库即可。

代码

读取淘宝联盟每日10点上新的xls文件

FileInputStream inputStream = new FileInputStream("/Users/aihe/Desktop/精选优质商品清单(内含优惠券)-2017-03-09.xls");
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
Workbook workbook = new HSSFWorkbook(poifsFileSystem);
HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(0);int rows = sheet.getPhysicalNumberOfRows();for (int i = 1; i < rows; i++) {
    HSSFRow row = sheet.getRow(i);     for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {        // TODO 对cell进行操作
         HSSFCell cell = row.getCell(j);
    }
}

读取XML内容,XML内容, 文件名为cat.xml

<?xml version="1.0" encoding="utf-8" ?><row>
    <field name="catid">1</field>
    <field name="catname">时尚女装</field>
    <field name="catid">2</field>
    <field name="catname">男装</field>
    <field name="catid">3</field>
    <field name="catname">母婴</field>
    <field name="catid">5</field>
    <field name="catname">食品</field>
    <field name="catid">6</field>
    <field name="catname">美妆</field>
    <field name="catid">7</field>
    <field name="catname">箱包</field>
    ...</row>
File file = new File("cat.xml");

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document document =  builder.parse(file);
document.getDocumentElement().normalize();

NodeList nodeList = document.getElementsByTagName("field");

LinkedList<String> catids = new LinkedList<>();
LinkedList<String> catNames = new LinkedList<>();for (int i = 0; i < nodeList.getLength(); i++) {     if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE){
           Element element = (Element) nodeList.item(i);           if (element.getAttribute("name").equals("catid")){
                catIds.add(element.getTextContent());
           }else if (element.getAttribute("name").equals("catname")){
                catNames.add(element.getTextContent())
           }
     }
}

System.out.println(catIds);
System.out.println(catNames);

结果:

[1, 2, 3, 5, 6, 7, 9, 11, 13, 14, 15, 16, 17]
[时尚女装, 男装, 母婴, 食品, 美妆, 箱包, 珠宝配饰, 文体用品, 居家百货, 家装家纺, 数码家电, 户外运动, 茶叶 ]

总结

程序比较简单,只是一些简单的小例子, 做一些记录。

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
1.1万
获赞与收藏
1544

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消