21xrx.com
2025-03-29 13:45:09 Saturday
文章检索 我的文章 写文章
Java操作Excel,实现往指定位置写入数据
2023-06-18 06:57:59 深夜i     16     0
Java Excel POI库

Java作为一门成熟的编程语言,在一些实际的操作中,对于Excel表格的操作也尤为常见。在Java中,操作Excel表格有多种方式,可以使用POI、JExcel等第三方库,还可以使用JDBC与ODBC驱动程序来连接Excel。本文将介绍使用POI库实现在Excel中往指定位置写入数据的方法,并附上代码和效果图,希望对大家有所帮助。

首先,我们需要在Java中引入POI库,这里演示使用的是POI 4.1.1版本。然后,我们定义Excel文件的路径、名称、Sheet名称、数据等信息。

String filePath = "C:/test/excel.xlsx";
String sheetName = "Sheet1";
String[] columnNames = "性别";
String[] row1 = "张三";
String[] row2 = "女";

接着,我们使用POI库读取Excel文件,并在指定的Sheet表格中往指定位置写入数据。

//读取Excel文件
FileInputStream file = new FileInputStream(filePath);
Workbook wb = new XSSFWorkbook(file);
//获取指定的Sheet表格
Sheet sheet = wb.getSheet(sheetName);
//定义单元格样式
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//写入表头数据
Row row = sheet.createRow(0);
for(int i = 0; i < columnNames.length; i++) {
  Cell cell = row.createCell(i);
  cell.setCellValue(columnNames[i]);
  cell.setCellStyle(cellStyle);
}
//写入数据
int rowIndex = 1;
Row newRow = sheet.createRow(rowIndex++);
for(int i = 0; i < row1.length; i++) {
  Cell cell = newRow.createCell(i);
  cell.setCellValue(row1[i]);
  cell.setCellStyle(cellStyle);
}
newRow = sheet.createRow(rowIndex++);
for(int i = 0; i < row2.length; i++) {
  Cell cell = newRow.createCell(i);
  cell.setCellValue(row2[i]);
  cell.setCellStyle(cellStyle);
}
//将Excel文件保存至指定路径
FileOutputStream fileOut = new FileOutputStream(filePath);
wb.write(fileOut);
fileOut.close();

最后,我们运行程序,保存Excel文件,查看效果。

![excel](https://user-images.githubusercontent.com/52039029/103627790-2d5fa780-4f7f-11eb-9d86-825dec6e96e1.png)

代码案例、效果图、POI库

  
  

评论区

请求出错了