org.apache.poi对更高excel2003文档的操作
1.导入jar包
dom4j-20040902.021138.jar
ooxml-schemas-1.1.jar
poi-3.9.jar
poi-ooxml-3.9.jar
xmlbeans-2.5.0.jar
2.范例代码
[java]
package xls;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.util.WorkbookUtil;
/**
* @description 读写excel2003文档
* @author YHZ
* @url http://blog.csdn.net/howareyoutodaysoft
* @qq 2481151614
* @date 2013-1-14
*
*/
public class Xls2003Util {
/**
* @param args
*/
public static void main(String[] args) {
Xls2003Util test = new Xls2003Util();
test.writeXls("C:\\Documents and Settings\\不了了之\\桌面\\写入2003.xls");
test.readXls("C:\\Documents and Settings\\不了了之\\桌面\\挂车未检.xls");
}
/**
* 写入2003版本的xls
*
* @param path
*/
private void writeXls(String path) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("new sheet");
HSSFRow row = sheet1.createRow(2);
row.createCell(0).setCellValue(1.1);
row.createCell(1).setCellValue(new java.util.Date());
row.createCell(2).setCellValue("a string内容信息");
row.createCell(3).setCellValue(true);
row.createCell(4).setCellType(HSSFCell.CELL_TYPE_ERROR);
HSSFSheet sheet2 = wb.createSheet(); // create with default names
HSSFRow row2 = sheet2.createRow(2);
row2.createCell(0).setCellValue(1.1);
row2.createCell(1).setCellValue(new java.util.Date());
final String name = "second sheet";
wb.setSheetName(1, WorkbookUtil.createSafeSheetName(name)); // setting
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream(path);
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取2003版本的xls文件
*
* @param path
*/
private void readXls(String path) {
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream(path);
POIFSFileSystem fs = new POIFSFileSystem(fileIn);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
System.out.println("开始行数:"+sheet.getFirstRowNum()+",结束行数:" + sheet.getLastRowNum());
for(int i=sheet.getFirstRowNum(); i<=sheet.getLastRowNum(); i++){
HSSFRow row = sheet.getRow(i);
System.out.println("第"+i+"行:");
for(int k=row.getFirstCellNum();k<row.getLastCellNum();k++){
System.out.print("cell内容:["+row.getCell(k).getRichStringCellValue()+"]");
}
System.out.println("");
row = null;
}
HSSFRow row = sheet.getRow(2);
if (row == null)
row = sheet.createRow(2);
HSSFCell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue("a test");
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}