`
ripotala
  • 浏览: 9781 次
  • 性别: Icon_minigender_1
  • 来自: 福州
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

POI的简单使用

 
阅读更多

我们通常使用EXCEL来编辑游戏里的各种数值。

在服务器端,EXCEL文件采用ApachePOI进行解析。<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

POI的代码很庞大,我们基本上只使用带HSSF相关的部分。

HSSF是HorribleSpreadSheetFormat的缩写,也即“讨厌的电子表格格式”。

也许HSSF的名字有点滑稽,就本质而言它是一个非常严肃、正规的API。

通过HSSF,我们可以用纯Java代码来读取、写入、修改Excel文件。

这里,我们只讨论读取的部分。

怎么加载一个EXCEL文件?

读取Excel文件时,首先生成一个POIFSFileSystem对象,

由POIFSFileSystem对象构造一个HSSFWorkbook,

该HSSFWorkbook对象就代表了Excel文档。

代码举例

POIFSFileSystemfs=newPOIFSFileSystem(newFileInputStream(PATH));

HSSFWorkbookworkbook=newHSSFWorkbook(fs);

怎么找到目标子表?

EXCEL中的子表在POI作为一个个HSSFSheet存在。

我们可以通过表名或该表在EXCEL的索引下标来获得。

如:我们要在chaos.xls中取出“宠物设置”这张子表,代码如下:

HSSFSheet sheet = workbook.getSheet("宠物设置");

当然,我们知道该表是文件中的第三个子表,也可能通过

HSSFSheet sheet = workbook.getSheetAt(2);

<!--EndFragment-->

来取得想要的子表。

不过我们在开发过程中配置文件可能在不断变化,因此不是使用表名检索更为安全。

怎么访问目标行/列?

取得想要的子表后,我们就根据实际需要从HSSFSheet中取得想要的数据了。

在POI中,每行记录为一个HSSFRow,每列数据为一个HSSFCell

如,我们在解析物品配置表的时候,先通过

HSSFRowcurrRow=sheet.getRow(currRow);

<!--EndFragment-->

取得某条物品记录。

然后再操作这条记录,获取我们想要的列数据。

HSSFCellidCell=currRow.getCell((short)0);

HSSFCellnameCell=currRow.getCell((short)1);

HSSFCelltypeCell=currRow.getCell((short)2);

HSSFCelldescCell=currRow.getCell((short)3);

HSSFCellpriceCell=currRow.getCell((short)4);

HSSFCellparam1Cell=currRow.getCell((short)5);

HSSFCellparam2Cell=currRow.getCell((short)6);

HSSFCelliconCell=currRow.getCell((short)7);

HSSFCellclassCell=currRow.getCell((short)8);

可以看出,每列数据都是一个HSSFCell.

接下来,我们把数据HSSFCell转换为我们实际想要的参数类型。

itemName=nameCell.getRichStringCellValue().getString();

itemDesc=descCell.getRichStringCellValue().getString();

itemType=(byte)typeCell.getNumericCellValue();

itemPrice=(int)priceCell.getNumericCellValue();

itemParam1=(int)param1Cell.getNumericCellValue();

itemParam2=(int)param2Cell.getNumericCellValue();

itemIcon=(byte)iconCell.getNumericCellValue();

itemClass=(byte)classCell.getNumericCellValue();

<!--EndFragment-->

对于数值类型的列,调用getNumericCellValue取得数值后再造型成基础类型。

对于字符串的列,需要调用getRichStringCellValue().getString();

这样,我们就把EXCEL里的数据转换为代码中要使用的数据了。

ItemcurrItem=newItem();

currItem.setItemID(itemID);

currItem.setItemName(itemName);

currItem.setItemType(itemType);

currItem.setItemPrice(itemPrice);

.....

<!--EndFragment-->

<!--EndFragment-->
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics