C#使用NPOI逐列更新excel
/// <summary>
/// 逐列更新excel文件
/// </summary>
/// <param name="data">为将要保存的数据,list《string》代表一列数据,有多少个就代表有多列数据(所有列上对齐)</param>
/// <param name="save_address">代表将要更新的excel表格地址,包括"文件名.xls"</param>
/// <param name="start_row">代表数据更新的起始行(1,2,3.......65536)最多支持65536行</param>
/// <param name="sart_column">代表数据更新的起始列(1,2,3......256)最多支持256列</param>
/// <param name="sheet_number">代表将要更新的sheet表的索引位置</param>
/// <returns>返回 true 代表更新成功,否则为更新失败</returns>
public static bool colUpdate(List<List<string>> data, string save_address,
int start_row, int sart_column, int sheet_number)//更新excel表格
{
FileStream writefile = null;
try
{
//如果传入参数合法
if (data != null && !string.IsNullOrEmpty(save_address) && start_row > 0 && sart_column > 0 && sheet_number > 0)
{
FileStream readfile = null;
HSSFWorkbook hssfworkbook = null;
ISheet sheet = null;
try
{
readfile = new FileStream(save_address, FileMode.Open, FileAccess.Read);
hssfworkbook = new HSSFWorkbook(readfile);
sheet = hssfworkbook.GetSheetAt(sheet_number - 1);
}
catch (Exception)
{
Console.WriteLine("NpoiOperateExcel.colUpdate方法加载被更新文件时产生了异常!");
}
finally
{
if (readfile != null) { readfile.Close(); }
}
if (sheet != null)
{
int columnIndex = sart_column - 1;//初始化起始列索引
foreach (List<string> list in data)
{
int rowIndex = start_row - 1;//初始化起始行索引
foreach (string str in list)
{
IRow row = sheet.GetRow(rowIndex);
if (row == null)
{
row = sheet.CreateRow(rowIndex);//在工作表中添加一行
}
ICell cell = row.GetCell(columnIndex);
if (cell == null)
{
cell = row.CreateCell(columnIndex);//在行中添加一列
}
cell.SetCellValue(str);//设置列的内容
rowIndex++;//行索引向后移动
}
columnIndex++;//列索引向后移动
}
writefile = new FileStream(save_address, FileMode.Create);
hssfworkbook.Write(writefile);
return true;//更新成功
}
else
{
return false;//更新失败
}
}
else
{
return false;//更新失败
}
}
catch (Exception)
{
Console.WriteLine("NpoiOperateExcel.colUpdate方法产生了异常!");
return false;//更新失败
}
finally
{
if (writefile != null) { writefile.Close(); }
}
}
来源: http://www.bubuko.com/infodetail-2220526.html