c# 使用NPOI 操作excel文件
本文关键字: excel, NPOI, nuget1,打开vs 在 nuget上搜索 npoi 安装对应版本;
2,程序代码引用命名空间
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
3, 读取excel到datatable的代码:下面代码需要说明的是,表头部分,如果命名不规范,可以直接保留“columns”+索引来命名。
/// <summary>
/// Excel导入成Datable
/// </summary>
/// <param name=”file”>导入路径(包含文件名与扩展名)</param>
/// <returns></returns>
public static DataTable ExcelToTable(string file)
{
DataTable dt = new DataTable();
IWorkbook workbook;
string fileExt = Path.GetExtension(file).ToLower();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
//XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
if (fileExt == “.xlsx”) { workbook = new XSSFWorkbook(fs); } else if (fileExt == “.xls”) { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
if (workbook == null) { return null; }
ISheet sheet = workbook.GetSheetAt(0);//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = 0; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn(“Columns” + i.ToString()));
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
}/// <summary>
/// 获取单元格类型
/// </summary>
/// <param name=”cell”></param>
/// <returns></returns>
private static object GetValueType(ICell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return “=” + cell.CellFormula;
}
}
4 ,数据处理完成以后,导出excel的代码:
/// <summary>
/// Datable导出成Excel
/// </summary>
/// <param name=”dt”></param>
/// <param name=”file”>导出路径(包括文件名与扩展名)</param>
public static void TableToExcel(DataTable dt, string file)
{
IWorkbook workbook;
string fileExt = Path.GetExtension(file).ToLower();
if (fileExt == “.xlsx”) { workbook = new XSSFWorkbook(); } else if (fileExt == “.xls”) { workbook = new HSSFWorkbook(); } else { workbook = null; }
if (workbook == null) { return; }
ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet(“Sheet1”) : workbook.CreateSheet(dt.TableName);//表头
IRow row = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
}//数据
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}//转为字节数组
MemoryStream stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();//保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
}
}
5,另外附上,选择或保存excel文件的代码:
打开excel:
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = false;
fileDialog.Title = “请选择旧文件”;
fileDialog.Filter = “所有文件(*xls*)|*.xls*”; //设置要选择的文件的类型
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string filename = fileDialog.FileName;//返回文件的完整路径
}保存excel:
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Title = “请设置导出文件”;fileDialog.Filter = “xlsx文件(*.xlsx)|*.xlsx”;
fileDialog.RestoreDirectory = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string savename = fileDialog.FileName;//返回文件的完整路径
}