java 写入excel 追加,Java - 追加excel

这篇博客讨论了如何使用Java的Apache POI库追加数据到Excel文件。作者遇到的问题是追加的数据只出现在最后一列,而无法正确填充所有列。他们分享了代码片段,并寻求解决此问题的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我需要追加excel。我写代码:

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.sql.ResultSet;

import java.sql.Statement;

import org.apache.poi.EncryptedDocumentException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.ss.usermodel.WorkbookFactory;

import javafx.collections.FXCollections;

import javafx.collections.ObservableList;

public class AppendExcel {

public static void main(String[] args) throws Exception {

String excelFilePath = "append.xlsx";

try {

FileInputStream inputStream = new FileInputStream(new File(excelFilePath));

Workbook workbook = WorkbookFactory.create(inputStream);

Sheet sheet = workbook.getSheetAt(0);

DbManagerSQL test = new DbManagerSQL();

String sql = "select distinct Code,Item,Description from MyTable";

Statement stmt = test.dbConnect().createStatement();

ResultSet rs = stmt.executeQuery(sql);

int rowCount = sheet.getLastRowNum();

while (rs.next()) {

Row row = sheet.createRow(++rowCount);

int columnCount = 0;

Cell cell = row.createCell(columnCount);

cell.setCellValue(rowCount);

cell = row.createCell(++columnCount);

cell.setCellValue((String) rs.getString(1));

cell.setCellValue((String) rs.getString(2));

cell.setCellValue((String) rs.getString(3));

}

inputStream.close();

FileOutputStream outputStream = new FileOutputStream("append.xlsx");

workbook.write(outputStream);

// workbook.close();

outputStream.close();

} catch (IOException | EncryptedDocumentException | InvalidFormatException ex) {

ex.printStackTrace();

}

}

}我的Excel有专栏

06ad9c4cc5152851c308475fcbd75ffd.png

但是当我追加Excel时,我得到了下一个

f191db7521335741fbabd0a563204b0d.png

它看起来像只记得最后一列。我认为这个箴言是在这行代码中

cell = row.createCell(++ columnCount);

但我现在不知道如何添加数据来获得像这样的excel

cdeecc1a841f155d18c5f4e318632548.png

任何想法???

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值