ExcelExportUtil.exportExcel方法上实现导出时加上序号
时间: 2023-12-06 16:02:47 浏览: 305
可以在 ExcelExportUtil.exportExcel 方法中添加一个参数 index,来实现导出时加上序号。具体实现方法如下:
1. 在 ExcelExportUtil 类中添加一个静态方法 getCellStyle,用于获取单元格样式:
```java
public static XSSFCellStyle getCellStyle(XSSFWorkbook workbook) {
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
return cellStyle;
}
```
2. 修改 ExcelExportUtil.exportExcel 方法,添加一个 int 类型的参数 index:
```java
public static void exportExcel(String title, String[] headers, List<Object[]> dataList, int index, OutputStream outputStream) throws IOException {
// 创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建工作表
XSSFSheet sheet = workbook.createSheet(title);
// 创建表头
XSSFRow headerRow = sheet.createRow(0);
XSSFCellStyle cellStyle = getCellStyle(workbook);
for (int i = 0; i < headers.length; i++) {
XSSFCell headerCell = headerRow.createCell(i);
headerCell.setCellValue(headers[i]);
headerCell.setCellStyle(cellStyle);
}
// 填充数据
for (int i = 0; i < dataList.size(); i++) {
Object[] data = dataList.get(i);
XSSFRow dataRow = sheet.createRow(i + 1);
XSSFCell indexCell = dataRow.createCell(0);
indexCell.setCellValue(i + index);
indexCell.setCellStyle(cellStyle);
for (int j = 0; j < data.length; j++) {
XSSFCell dataCell = dataRow.createCell(j + 1);
dataCell.setCellValue(String.valueOf(data[j]));
dataCell.setCellStyle(cellStyle);
}
}
// 输出到输出流
workbook.write(outputStream);
workbook.close();
}
```
3. 在调用 ExcelExportUtil.exportExcel 方法时,传入序号的起始值即可:
```java
List<Object[]> dataList = new ArrayList<>();
dataList.add(new Object[]{"张三", "男", 20});
dataList.add(new Object[]{"李四", "女", 21});
dataList.add(new Object[]{"王五", "男", 22});
try (OutputStream outputStream = new FileOutputStream("test.xlsx")) {
String[] headers = {"序号", "姓名", "性别", "年龄"};
ExcelExportUtil.exportExcel("学生信息表", headers, dataList, 1, outputStream);
}
```
这样就可以实现导出时加上序号的功能了。
阅读全文