您的位置:首页 > 其它

使用POI操作Excel

2008-12-27 16:03 447 查看
Apache的Jakata项目POI(http://poi.apache.org),用来操作Excel,并能满足大部分需要.POI下面有几个子项目,其中HSSF+XSSF项目(http://poi.apache.org/spreadsheet/index.html)用来实现Excel读写的.

POI组件下载后,将.jar包加入到classpath,或者复制到WEB-INF/classes下即可.

public static void main(String[] args) {
try {

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow((short) 0);
// Create a cell and put a value in it.
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue(1);

// Or do it on one line.
row.createCell((short) 1).setCellValue(1.2);
row.createCell((short) 2).setCellValue("This is a string");
row.createCell((short) 3).setCellValue(true);

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

程序首先创建一个HSSFWorkbook实例,它相当于一个Excel文件,然后创建HSSFSheet,它相当于一个Excel文件的一页.在创建了页对象之后,就可以向该页中添加内容了.POI将Excel文件页面中的每行用HSSFRow来表示,而每个单元格用HSSFCell对象来表示.向页面添加内容时,首先创建行,然后再创建行所包含的单元格,设置单元格中的数据.向行中添加单元格时,行的列是以0进行索引的.最后调用HSSFWorkbook的write方法输出添加好内容的Excel文件.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: