我写的winform程序,现在要实现把一些数据写入到Excel文件,我在网上查到用NPIO可以向Excel文件中写数据。可是现在每次点击butten1都会把之前写入的数据覆盖掉,我现在要实现能向Excel文件中追加数据,不知道怎么实现,望高手指教。下面是我写的代码,可以实现写数据,但不能追加。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using System.IO;namespace Excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
HSSFWorkbook workbook = new HSSFWorkbook();//创建Excel文件
HSSFSheet sheet = workbook.CreateSheet();//创建页
HSSFRow row = sheet.CreateRow(0);//创建行
HSSFCell cell = row.CreateCell(0, HSSFCell.ENCODING_COMPRESSED_UNICODE);
cell.SetCellValue("hello");//设置一格
using (FileStream stream = new FileStream(@"C:\1.xls", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
workbook.Write(stream);
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using System.IO;namespace Excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
HSSFWorkbook workbook = new HSSFWorkbook();//创建Excel文件
HSSFSheet sheet = workbook.CreateSheet();//创建页
HSSFRow row = sheet.CreateRow(0);//创建行
HSSFCell cell = row.CreateCell(0, HSSFCell.ENCODING_COMPRESSED_UNICODE);
cell.SetCellValue("hello");//设置一格
using (FileStream stream = new FileStream(@"C:\1.xls", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
workbook.Write(stream);
}
}
}
}
这个地方你用的是打开或者创建
也就是可以覆盖你在FileMode.后面看还有其它几个,其中有一个A开头的可实现
{
_hssfworkbook = new HSSFWorkbook(OpenFileStream(filePath));
_currentSheet = _hssfworkbook.GetSheetAt(0);
_row = CurrentSheet.GetRow(0);
// _row 之后就可以再追加了!
return this;
}