Java读写Excel表格数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ceovip/article/details/82964487

开发中有时候需要把一些数据记录在Excel表格中,便于观察分析数据。这里操作Excel表格使用的是jxl.jar,jxl.jar是java操作Excel的一个工具类库,同样的工具类还有apache的poi,在小数据量时jxl快于poi,在大数据量时poi要快于jxl。但差距都不明显。

我们直接看下面两个读写Excel表格的简单示例:

写Excel表格数据:

	private static void writeExcel() throws IOException, RowsExceededException,
			WriteException {
		
		File xlsFile = new File("jxl.xls");
		// 创建一个工作簿
		WritableWorkbook workbook = Workbook.createWorkbook(xlsFile);
		// 创建一个工作表
		WritableSheet sheet = workbook.createSheet("sheet1", 0);
		// 向行和列中写数据
		for (int row = 0; row < 10; row++) {
			for (int col = 0; col < 10; col++) {
				// 向工作表中添加数据
				sheet.addCell(new Label(col, row, "data" + row + col));
			}
		}
		workbook.write();
		workbook.close();
	}

写完效果如下:
写入数据

如果读取项目下的students.xls表格,数据如下:
读数据

读数据示例代码:

	private static void readExcel() throws BiffException, IOException {
		File xlsFile = new File("students.xls");
		// 获得工作簿对象
		Workbook workbook = Workbook.getWorkbook(xlsFile);
		// 获得所有工作表
		Sheet[] sheets = workbook.getSheets();
		// 遍历工作表
		if (sheets != null) {
			for (Sheet sheet : sheets) {
				// 获得行数
				int rows = sheet.getRows();
				// 获得列数
				int cols = sheet.getColumns();
				// 读取数据
				for (int row = 0; row < rows; row++) {
					for (int col = 0; col < cols; col++) {
						Cell cell = sheet.getCell(col, row);   
	                    System.out.print(cell.getContents() + " ");   
					}
					System.out.println();
				}
			}
		}
		workbook.close();
	}

输出效果:
输出数据

猜你喜欢

转载自blog.csdn.net/ceovip/article/details/82964487