关于POI操作Excel的详细步骤

关于POI选择

我这里使用的是4.0.1版本的。需要导入:poi-4.0.1.jar和poi-ooxml-4.0.1.jar,这两个jar包。


97-2003版本的Excel操作方法

读取Excel表格

private HSSFWorkbook wb = null;								//excel操作对象
private HSSFSheet sheet = null;									//表格对象
private HSSFRow row = null;										//定义行对象
private HSSFCell cell = null; 										//定义列对象

File file = new File(文件名);
FileInputStream fis = null;											//文件输入流
POIFSFileSystem fs = null;
try {
			fis = new FileInputStream(file);
			fs = new POIFSFileSystem(fis);
			wb = new HSSFWorkbook(fs);
			sheet = wb.getSheetAt(0);										/第一张表
			int firstRowNum = sheet.getFirstRowNum();			
			row = sheet.getRow(firstRowNum);						//获取第一行
			short lastCellNum = row.getLastCellNum();			//获取多少列
			while(i <= lastCellNum ) {
				cell = row.getCell(i);
				cell.setCellType(CellType.STRING);
				String string1 = cell.getStringCellValue();
				++i;
			}
	} catch (FileNotFoundException e) {
			e.printStackTrace();
	} catch (IOException e) {
			e.printStackTrace();
	} finally {
				//关闭资源
				try {
					fis.close();
					fs.close();
					wb.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	}

2007版本以上Excel操作方法

读取Excel表格

private XSSFWorkbook xssfWorkbook = null;
private FileInputStream fis = null;
private XSSFSheet sheetAt = null;
private XSSFRow row = null;
private XSSFCell cell = null;

File file = new File(文件名);
try {
			fis = new FileInputStream(file);
			xssfWorkbook = new XSSFWorkbook(fis);
			sheetAt = xssfWorkbook.getSheetAt(0);
			int firstRowNum = sheetAt.getFirstRowNum();				//获取第一行
			row = sheetAt.getRow(firstRowNum);
			
			short lastCellNum = row.getLastCellNum();					//获取多少列
			while(i < lastCellNum) {
				cell = row.getCell(i);
				cell.setCellType(CellType.STRING);
				String string1 = cell.getStringCellValue();
				++i;
			}	
	} catch (IOException e) {
			e.printStackTrace();
	} finally {
		//关闭资源
		if(fis != null) {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(xssfWorkbook != null) {
			try {
				xssfWorkbook.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

写入Excel表格

XSSFWorkbook xssfWorkbook = null;
FileOutputStream fos = null;
XSSFSheet createSheet = null;
XSSFRow createRow = null;
XSSFCell createCell = null;
int size = 10;
File file = new File(文件名);	
try {
			xssfWorkbook = new XSSFWorkbook();
			createSheet = xssfWorkbook.createSheet();
			createRow = createSheet.createRow(0);
			
			for(int i = 0; i < size; ++i) {
				createCell = createRow.createCell(i);
				createCell.setCellType(CellType.STRING);
				createCell.setCellValue(“内容”);
			}
			fos = new FileOutputStream(file);
			xssfWorkbook.write(fos);
}catch(IOException e) {
			e.printStackTrace();
}finally {
		try {
			fos.close();
			xssfWorkbook.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
}

其他的方法可以查看文档使用,以上只是poi读取、写入excel的简单操作。记录下来,以便以后使用。

发布了45 篇原创文章 · 获赞 11 · 访问量 3892

猜你喜欢

转载自blog.csdn.net/qq_42197800/article/details/103810572