java模拟excel排序_Apache-POI在excel中排序行

要对行进行排序,您需要:

将所有行复制到temp

在temp中排序行

从工作表中删除所有行

使用temp中已排序行的值创建新行

public static void sortSheet(Workbook workbook, Sheet sheet) {

List rows = Lists.newArrayList(sheet.rowIterator());

rows.sort(Comparator.comparing(cells -> cells.getCell(0).getStringCellValue()));

removeAllRows(sheet);

for (int i = 0; i < rows.size(); i++) {

Row newRow = sheet.createRow(i);

Row sourceRow = rows.get(i);

// Loop through source columns to add to new row

for (int j = 0; j < sourceRow.getLastCellNum(); j++) {

// Grab a copy of the old/new cell

Cell oldCell = sourceRow.getCell(j);

Cell newCell = newRow.createCell(j);

// If the old cell is null jump to next cell

if (oldCell == null) {

newCell = null;</

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我会为您提供一个简单的 Apache POI 工具类的使用示例。 首先,您需要在您的项目引入 Apache POI 的依赖包,如果您使用 Maven,可以在 `pom.xml` 文件添加以下代码: ```xml <dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> </dependencies> ``` 接下来,我们可以创建一个简单的 Java 类来演示如何使用 Apache POI。 ```java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelWriter { public static void main(String[] args) { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("Sheet1"); // 创建第一并填写数据 Row row = sheet.createRow(0); Cell cell1 = row.createCell(0); cell1.setCellValue("姓名"); Cell cell2 = row.createCell(1); cell2.setCellValue("年龄"); // 创建第二并填写数据 Row row2 = sheet.createRow(1); Cell cell3 = row2.createCell(0); cell3.setCellValue("张三"); Cell cell4 = row2.createCell(1); cell4.setCellValue(20); // 将数据写入 Excel 文件 try { FileOutputStream outputStream = new FileOutputStream(new File("output.xlsx")); workbook.write(outputStream); workbook.close(); outputStream.close(); System.out.println("数据写入成功"); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码将创建一个名为 `Sheet1` 的 Excel 格,并在第一填写了 `姓名` 和 `年龄` 字段,第二填写了 `张三` 和 `20` 的数据。最后将数据写入名为 `output.xlsx` 的 Excel 文件。 希望这个简单的示例能够帮助您了解 Apache POI 的使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值