poi进行xlsx 复制一行_使用Apache POI操作Excel文件---在已有的Excel文件中插入一行新的数据...

本文档展示了如何使用Apache POI库在已存在的Excel文件(xlsx格式)中插入一行新的数据。通过创建一个新的XSSFRow对象并设置单元格值,然后将该行插入指定的工作表和行索引位置,最终保存更新后的Excel文件。

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

packageorg.test;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importorg.apache.poi.xssf.usermodel.XSSFCell;importorg.apache.poi.xssf.usermodel.XSSFRow;importorg.apache.poi.xssf.usermodel.XSSFSheet;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;public classPoiTesst {//当前文件已经存在

private String excelPath = "F:\\123abcdefg.xlsx";//从第几行插入进去

private int insertStartPointer = 3;//在当前工作薄的那个工作表单 (sheet页名称)

private String sheetName = "sheet1";/*** 总的入口方法*/

public static voidmain(String[] args) {

PoiTesst crt= newPoiTesst();

crt.insertRows();

}/*** 在已有的Excel文件中插入一行新的数据的入口方法*/

public voidinsertRows() {

XSSFWorkbook wb=returnWorkBookGivenFileHandle();

XSSFSheet sheet1=wb.getSheet(sheetName);

XSSFRow row=createRow(sheet1, insertStartPointer);

createCell(row);

saveExcel(wb);

}/*** 找到需要插入的行数,并新建一个POI的row对象

*@paramsheet

*@paramrowIndex

*@return

*/

privateXSSFRow createRow(XSSFSheet sheet, Integer rowIndex) {

XSSFRow row= null;if (sheet.getRow(rowIndex) != null) {int lastRowNo =sheet.getLastRowNum();

sheet.shiftRows(rowIndex, lastRowNo,1);

}

row=sheet.createRow(rowIndex);returnrow;

}/*** 创建要出入的行中单元格

*@paramrow

*@return

*/

privateXSSFCell createCell(XSSFRow row) {

XSSFCell cell= row.createCell((short) 0);

cell.setCellValue(999999);

row.createCell(1).setCellValue(1.2);

row.createCell(2).setCellValue("This is a string cell");returncell;

}/*** 保存工作薄

*@paramwb*/

private voidsaveExcel(XSSFWorkbook wb) {

FileOutputStream fileOut;try{

fileOut= newFileOutputStream(excelPath);

wb.write(fileOut);

fileOut.close();

}catch(FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}/*** 得到一个已有的工作薄的POI对象

*@return

*/

privateXSSFWorkbook returnWorkBookGivenFileHandle() {

XSSFWorkbook wb= null;

FileInputStream fis= null;

File f= newFile(excelPath);try{if (f != null) {

fis= newFileInputStream(f);

wb= newXSSFWorkbook(fis);

}

}catch(Exception e) {return null;

}finally{if (fis != null) {try{

fis.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}returnwb;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值