2024年3月8日发(作者:)

NPOI如何向已存在的Excel文件中插入一行数据

很多例子在利用NPOI向Excel写数据时,都是创建一个新的文件,或者通过模版创建新文件,然后再写数据,输出新的文件。

现在就只需要在已有的Excel中插入几条数据,该如何实现?

回复讨论(解决方案)

参考:

NPOI 插入行

//假如我要在指定的表的第3行插入3行,可以使用这样写:

int InsertRowIndex=2;//指定在第几行插入,我们这里测试用第3行,对应NPOI的索引值2,因为从0起

int InsertRowCount=3;//要插入的行数

HSSFWorkbook Workbook=NPOIOpenExcel(@"E:");//打开工作薄

HSSFSheet mySheet= etAt(SheetIndex);//获取工作表

HSSFRow mySourceStyleRow=(InsertRowIndex-1);//获取源格式行

//调用插入行方法

MyInsertRow(mySheet,InsertRowIndex,InsertRowCount,mySourceStyleRow);

//参数说明

//第一个:指定操作的Sheet。

//第二个:指定在第几行指入(插入行的位置)

//第三个:指定要插入多少行

//第四个:源单元格格式的行,

//函数部分:

public HSSFWorkbook NPOIOpenExcel(string FileName)

{

HSSFWorkbook MyHSSFWorkBook;

Stream MyExcelStream = OpenClasspathResource(FileName);

MyHSSFWorkBook = new HSSFWorkbook(MyExcelStream);

return MyHSSFWorkBook;

}

private void MyInsertRow(HSSFSheet sheet, int 插入行, int 插入行总数, HSSFRow 源格式行)

{

#region 批量移动行

sheet

.ShiftRows

(

插入行, //--开始行

sheet

.LastRowNum, //--结束行

插入行总数, //--移动大小(行数)--往下移动

true, //是否复制行高

false, //是否重置行高

true //是否移动批注

);

#endregion

#region 对批量移动后空出的空行插,创建相应的行,并以插入行的上一行为格式源(即:插入行-1的那一行)

for (int i = 插入行; i < 插入行 + 插入行总数 - 1; i++)

{

HSSFRow targetRow = null;

HSSFCell sourceCell = null;

HSSFCell targetCell = null;

targetRow = Row(i + 1);

for (int m = 源格式行.FirstCellNum; m < 源行.LastCellNum; m++)

{

sourceCell = 源格式行.GetCell(m);

if (sourceCell == null)

continue;

targetCell = Cell(m);

ng = ng;

yle = yle;

lType(pe);

}

//CopyRow(sourceRow, targetRow);

//w(sheet, sourceRow, targetRow);

}

HSSFRow firstTargetRow = (插入行);

HSSFCell firstSourceCell = null;

HSSFCell firstTargetCell = null;

for (int m = 源格式行.FirstCellNum; m < 源格式格式

行.LastCellNum; m++)

{

firstSourceCell = 源格式行.GetCell(m);

if (firstSourceCell == null)

continue;

firstTargetCell = Cell(m);

ng = ng;

yle = yle;

lType(pe);

}

#endregion

}

使用NPOI操作Excel,实现插入行

Private Sub InsertRows(ByRef targetSheet As HSSFSheet, ByVal fromRowIndex As Integer, ByVal rowCount As Integer)

'将fromRowIndex行以后的所有行向下移动rowCount行,保留行高和格式

ows(fromRowIndex + 1, wNum, rowCount, True, False, True)

'取得源格式行

Dim rowSource = (fromRowIndex)

Dim rowstyle = le

For rowIndex = fromRowIndex + 1 To fromRowIndex + rowCount

'新建插入行

Dim rowInsert = Row(rowIndex)

le = rowstyle

'设置插入行的行高

=

For colIndex = 0 To llNum

'新建插入行的所有单元格,并复制源格式行相应单元格的格式

Dim cellSource = l(colIndex)

Dim cellInsert = Cell(colIndex)

If Not IsNothing(cellSource) Then

yle = yle

End If

Next

Next

End Sub

参考:

NPOI 插入行

//假如我要在指定的表的第3行插入3行,可以使用这样写:

int InsertRowIndex=2;//指定在第几行插入,我们这里测试用第3行,对应NPOI的索引值2,因为从0起

int InsertRowCount=3;//要插入的行数

HSSFWorkbook Workbook=NPOIOpenExcel(@"E:");//打开工作薄

HSSFSheet mySheet= etAt(SheetIndex);//获取工作表

HSSFRow mySourceStyleRow=(InsertRowIndex-1);//获取源格式行

//调用插入行方法

MyInsertRow(mySheet,InsertRowIndex,InsertRowCount,mySourceStyleRow);

//参数说明

//第一个:指定操作的Sheet。

//第二个:指定在第几行指入(插入行的位置)

//第三个:指定要插入多少行

//第四个:源单元格格式的行,

//函数部分:

public HSSFWorkbook NPOIOpenExcel(string FileName)

{

HSSFWorkbook MyHSSFWorkBook;

Stream MyExcelStream = OpenClasspathResource(FileName);

MyHSSFWorkBook = new HSSFWorkbook(MyExcelStream);

return MyHSSFWorkBook;

}

private void MyInsertRow(HSSFSheet sheet, int 插入行, int 插入行总数, HSSFRow 源格式行)

{

#region 批量移动行

sheet

.ShiftRows

(

插入行, //--开始行

sheet

.LastRowNum, //--结束行

插入行总数, //--移动大小(行数)--往下移动

true, //是否复制行高

false, //是否重置行高

true //是否移动批注

);

#endregion

#region 对批量移动后空出的空行插,创建相应的行,并以插入行的上一行为格式源(即:插入行-1的那一行)

for (int i = 插入行; i < 插入行 + 插入行总数 - 1; i++)

{

HSSFRow targetRow = null;

HSSFCell sourceCell = null;

HSSFCell targetCell = null;

targetRow = Row(i + 1);

for (int m = 源格式行.FirstCellNum; m < 源行.LastCellNum; m++)

{

sourceCell = 源格式行.GetCell(m);

if (sourceCell == null)

continue;

targetCell = Cell(m);

ng = ng;

yle = yle;

lType(pe);

}

//CopyRow(sourceRow, targetRow);

//w(sheet, sourceRow, targetRow);

}

格式

HSSFRow firstTargetRow = (插入行);

HSSFCell firstSourceCell = null;

HSSFCell firstTargetCell = null;

for (int m = 源格式行.FirstCellNum; m < 源格式行.LastCellNum; m++)

{

firstSourceCell = 源格式行.GetCell(m);

if (firstSourceCell == null)

continue;

firstTargetCell = Cell(m);

ng = ng;

yle = yle;

lType(pe);

}

#endregion

}

使用NPOI操作Excel,实现插入行

Private Sub InsertRows(ByRef targetSheet As HSSFSheet, ByVal fromRowIndex As Integer, ByVal rowCount As Integer)

'将fromRowIndex行以后的所有行向下移动rowCount行,保留行高和格式

ows(fromRowIndex + 1, wNum, rowCount, True, False, True)

'取得源格式行

Dim rowSource = (fromRowIndex)

Dim rowstyle = le

For rowIndex = fromRowIndex + 1 To fromRowIndex + rowCount

'新建插入行

Dim rowInsert = Row(rowIndex)

le = rowstyle

'设置插入行的行高

=

For colIndex = 0 To llNum

'新建插入行的所有单元格,并复制源格式行相应单元格的格式

Dim cellSource = l(colIndex)

Dim cellInsert = Cell(colIndex)

If Not IsNothing(cellSource) Then

yle = yle

End If

Next

Next

End Sub

谢谢你的回答!

但我测试时没有成功,

有两个问题:

我使用的是NPOI 2.0 ,因此提示第一个错误 ShiftRows方法是没有6个参数的重载

无OpenClasspathResource 方法,我用FileOpen代替了。

修改以上两个问题后 ,程序能够运行,但没对Excel进行过任何修改。

问题出在你的修改没有保存会Excel。

OpenClasspathResource和WriteToFile函数补上了。下面是我的测试代码(官网下的NPIO 2.0版本):

using System;

using ;

using ;

using del;

using del;

namespace NPOISample

{

///

/// Description of MainForm.

///

public class MainForm : Form

{

#region er

///

/// Designer variable used to keep track of non-visual components.

///

private iner components = null;

///

/// Disposes resources used by the form.

///

/// true if managed resources should be disposed; otherwise, false.

protected override void Dispose(bool disposing)

{

if (disposing) {

if (components != null) {

e();

}

}

e(disposing);

}

///

/// This method is required for Windows Forms designer support.

/// Do not change the method contents inside the source code editor. The Forms designer might

/// not be able to load this method if it was changed manually.

///

private void InitializeComponent()

{

1 = new ();

dLayout();

//

// button1

//

on = new (12, 12);

= "button1";

= new (75, 23);

ex = 0;

= "插入行";

ualStyleBackColor = true;

+= new andler(1Click);

//

// MainForm

//

aleDimensions = new (6F,

12F);

aleMode = ;

Size = new (128, 46);

(1);

= "MainForm";

= "NPOISample";

Layout(false);

}

private button1;

#endregion

public MainForm()

{

//

// The InitializeComponent() call is required for Windows Forms designer support.

//

InitializeComponent();

//

// TODO: Add constructor code after the InitializeComponent() call.

//

}

private string DataDir = rectory;

void Button1Click(object sender, EventArgs e)

{

d = false;

int InsertRowIndex=2;//指定在第几行插入,我们这里测试用第3行,对应NPOI的索引值2,因为从0起

int InsertRowCount=3;//要插入的行数

IWorkbook Workbook=NPOIOpenExcel(DataDir + @"");//打开工作薄

ISheet mySheet= etAt(SheetIndex);//获取工作表

IRow mySourceStyleRow=(InsertRowIndex-1);//获取源格式行

//调用插入行方法

MyInsertRow(mySheet, InsertRowIndex, InsertRowCount, mySourceStyleRow);

WriteToFile(Workbook, DataDir + @"");

d = true;

}

public IWorkbook NPOIOpenExcel(string FileName)

{

IWorkbook MyWorkBook;

Stream MyExcelStream = OpenClasspathResource(FileName);

MyWorkBook = new HSSFWorkbook(MyExcelStream);

return MyWorkBook;

}

/**

* Opens a test sample file from the 'data' sub-package of this class's package.

* @return null if the sample file is1 not deployed on the classpath.

*/

private Stream OpenClasspathResource(String fileName)

{

FileStream file = new FileStream(fileName, ,

);

return file;

}

private void WriteToFile(IWorkbook workbook, String fileName)

{

//Write the stream data of workbook to the root directory

FileStream file = new FileStream(fileName, ,

);

(file);

();

}

//参数说明

//第一个:指定操作的Sheet。

//第二个:指定在第几行指入(插入行的位置)

//第三个:指定要插入多少行

//第四个:源单元格格式的行,

private void MyInsertRow(ISheet sheet, int 插入行, int 插入行总数, IRow 源格式行)

{

#region 批量移动行

ows(

插入行, //--开始行

wNum, //--结束行

插入行总数, //--移动大小(行数)--往下移动

true, //是否复制行高

false//, //是否重置行高

//true //是否移动批注

);

#endregion

#region 对批量移动后空出的空行插,创建相应的行,并以插入行的上一行为格式源(即:插入行-1的那一行)

for (int i = 插入行; i < 插入行 + 插入行总数 - 1; i++)

{

IRow targetRow = null;

ICell sourceCell = null;

ICell targetCell = null;

targetRow = Row(i + 1);

for (int m = 源格式行.FirstCellNum; m < 源格行.LastCellNum; m++)

{

sourceCell = 源格式行.GetCell(m);

if (sourceCell == null)

continue;

targetCell = Cell(m);

//targetCell..Encoding = ng;

yle = yle;

lType(pe);

}

//CopyRow(sourceRow, targetRow);

//w(sheet, sourceRow, targetRow);

}

IRow firstTargetRow = (插入行);

ICell firstSourceCell = null;

ICell firstTargetCell = null;

for (int m = 源格式行.FirstCellNum; m < 源格行.LastCellNum; m++)

{

firstSourceCell = 源格式行.GetCell(m);

if (firstSourceCell == null)

continue;

firstTargetCell = Cell(m);

//ng = ng;

式式

yle = yle;

lType(pe);

}

#endregion

}

}

}

谢谢你的回答!

但我测试时没有成功,

有两个问题:

我使用的是NPOI 2.0 ,因此提示第一个错误 ShiftRows方法是没有6个参数的重载

无OpenClasspathResource 方法,我用FileOpen代替了。

修改以上两个问题后 ,程序能够运行,但没对Excel进行过任何修改。

直接覆盖原有excel文件

///

/// 用模板导出Excel

///

///

/// 导出路径

/// 模板路径

/// 从第几行开始写数据,从1开始

public static void ExportExcelByTemple(ble dtSource, string strFileName, string templetPath, int rowHeight, int startRow)

{

try

{

HSSFWorkbook workbook = getWorkBook(templetPath);

HSSFSheet sheet = getSheet(workbook);

writeData(workbook, sheet, dtSource, strFileName, rowHeight, startRow);

saveData(workbook, strFileName);

}

catch (Exception ex)

{

(ex);

throw ex;

}

}

///

/// 解析Excel模板,返回WorkBook

///

///

///

private static HSSFWorkbook getWorkBook(string templetPath)

{

FileStream file = new FileStream(templetPath, , );

HSSFWorkbook workbook = new HSSFWorkbook(file);

return workbook;

}

///

/// 返回Sheet

///

///

///

private static HSSFSheet getSheet(HSSFWorkbook workbook)

{

return etAt(0);

}

///

///

///

///

///

///

///

///

///

///

private static void writeData(HSSFWorkbook workbook, HSSFSheet sheet, ble dtSource, string strFileName, int rowHeight, int startRow)

{

// //填充表头

HSSFRow dataRow = new HSSFRow();

//填充内容

for (int i = 0; i < ; i++)

{

dataRow = Row(i + startRow - 1);

= (short)(rowHeight * 20);

for (int j = 0; j < ; j++)

{

string drValue = [i][j].ToString();

Cell(j).SetCellValue(drValue);

}

}

}

///

/// 保存数据

///

///

///

private static void saveData(HSSFWorkbook workbook, string strFileName)

{

//保存

using (MemoryStream ms = new MemoryStream())

{

using (FileStream fs = new FileStream(strFileName, , ))

{

(fs);

}

}

}

可能感兴趣

【原】.Net创建Excel文件(插入数据、修改格式、生成图表)

的方法 .

【原】.Net创建Excel文件(插入数据、修改格式、生成图表).Net创建Excel文件(插入数据、修改格式、生成图表)的方法一起谈.NET技术,.Net创建Excel文件(插入数据、修改格式、.Net中DataGridview数据如何导出到excel表

hdu1045Fire Net (一行变多行,一列变多列,最小顶点覆盖)

.Net中利用config文件来保存信息

.NET数据库连接中的对象

.net中的mvc数据验证疑问解决办法

的方法

()

生成图表)的方法

From : /topics/390817921