在C#中有很多种读取excel表格的方式有oldb、epplus、npoi、文件流,今天在使用net5框架不能使用oldb方式读取,于是使用了npoi,本文介绍一下npoi读取方式,其他方式读取请移步另一篇文章https://blog.csdn.net/qq_39569480/article/details/105573807
在包管理器安装npoi
这里在安装2.6时报了个错,可参考我零一篇文章http://t.csdn.cn/YuXHW
https://blog.csdn.net/qq_39569480/article/details/130653685?spm=1001.2014.3001.5501
话不多说上代码,读取表格
调用
using 引用
using NPOI.HSSF.UserModel;//导出xls格式用HSSF
using NPOI.XSSF.UserModel;//导出xlsx格式用XSSF
using NPOI.SS.UserModel;
string path = @"G:\新建文件夹\上传数据.xls";
var (Result, Msg, Dt) = ExcelToTable(path);
/// <summary>
/// Excel导入成DataTble
/// </summary>
/// <param name="file">导入路径(包含文件名与扩展名)</param>
/// <returns></returns>
public static (bool,string, DataTable) ExcelToTable(string file)
{
try
{
DataTable dt = new DataTable();
IWorkbook workbook;
string fileExt = Path.GetExtension(file).ToLower();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
if (workbook == null) { return (false,"没有读取到数据",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 (true,"", dt);
}
catch (Exception e)
{
return (false,e.Message,null);
}
}
/// <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:
return null;
case CellType.Boolean:
return cell.BooleanCellValue;
case CellType.Numeric:
return cell.NumericCellValue;
case CellType.String:
return cell.StringCellValue;
case CellType.Error:
return cell.ErrorCellValue;
case CellType.Formula:
default:
return "=" + cell.CellFormula;
}
}
写入表格 xls、xlsx
调用
//这里先调用上边读取excel文件的方法 把数据读到datatable中 然后修改了两个列的值再写回到excel文件中
string path = @"G:\新建文件夹\上传数据.xls";
var (Result, Msg, Dt) = ExcelToTable(path);
if (Result)
{
for (int i = 0; i < Dt.Rows.Count; i++)
{
Dt.Rows[i]["上传结果"] = "成功";
Dt.Rows[i]["上传信息"] = "12312312";
}
bool asads= DataTableToExcel(Dt, path);
MessageBox.Show(asads.ToString());
}
else
{
MessageBox.Show(Result.ToString()+ Msg);
}
/// <summary>
/// 将datatable写入到excel(xls)
/// </summary>
/// <param name="dt">datatable</param>
/// <param name="filepath">写入的文件路径</param>
/// <returns></returns>
public static bool DataTableToExcel(DataTable dt, string filepath)
{
bool result = false;
IWorkbook workbook = null;
FileStream fs = null;
IRow row = null;
ISheet sheet = null;
ICell cell = null;
try
{
if (dt != null && dt.Rows.Count > 0)
{
workbook = new HSSFWorkbook();
sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数
string cellnum;
//设置列头
row = sheet.CreateRow(0);//excel第一行设为列头
for (int c = 0; c < columnCount; c++)
{
cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
}
//设置每行每列的单元格,
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i + 1);
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);//excel第二行开始写入数据
//cell.SetCellValue(dt.Rows[i][j].ToString());
//保存单元格格式为数字
if (j < 2)
{
cell.SetCellValue(dt.Rows[i][j].ToString());
}
else
{
SetCellValue(cell, dt.Rows[i][j]);
//if (dt.Rows[i][j] is DBNull)
//{
// cell.SetCellValue(dt.Rows[i][j].ToString());
//}
//else
//{
// cellnum = Convert.ToString(dt.Rows[i][j].ToString());
// cell.SetCellValue(cellnum);
//}
}
}
}
if (System.IO.File.Exists(filepath))
{
if (MessageBox.Show("该文件已存在!确定覆盖吗?", "WARNING", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
File.Delete(filepath);
}
else
{
return false;
}
}
using (fs = File.OpenWrite(filepath))
{
workbook.Write(fs,true);//向打开的这个xls文件中写入数据
result = true;
}
}
return result;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
if (fs != null)
{
fs.Close();
}
return false;
}
}
/// <summary>
/// Datable导出成Excel(xlsx)
/// </summary>
/// <param name="dt"></param>
/// <param name="file">导出路径(包括文件名与扩展名)</param>
public static (bool,string) TableToExcel(DataTable dt, string file)
{
try
{
IWorkbook workbook;
string fileExt = Path.GetExtension(file).ToLower();
workbook = new XSSFWorkbook();导出xls格式用HSSF 导出xlsx格式用XSSF
ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("sheet0") : 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());
}
}
//保存为Excel文件
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms, true);
//ms.Close();
//ms.Dispose();
}
using (FileStream fs = new FileStream(file, FileMode.Create/*, FileAccess.Write*/))
{
workbook.Write(fs, true);
//fs.Close();
//workbook = null;
}
return (true,"");
}
catch (Exception e)
{
return (false,e.Message);
}
}
/// <summary>
/// 获取数据类型并设置单元格数据类型写入到单元格
/// </summary>
/// <param name="cell">目标单元格</param>
/// <param name="obj">数据值</param>
/// <returns></returns>
public static void SetCellValue(ICell cell, object obj)
{
if (obj.GetType() == typeof(int))
{
cell.SetCellValue((int)obj);
}
else if (obj.GetType() == typeof(double))
{
cell.SetCellValue((double)obj);
}
else if (obj.GetType() == typeof(IRichTextString))
{
cell.SetCellValue((IRichTextString)obj);
}
else if (obj.GetType() == typeof(string))
{
cell.SetCellValue(obj.ToString());
}
else if (obj.GetType() == typeof(DateTime))
{
cell.SetCellValue((DateTime)obj);
}
else if (obj.GetType() == typeof(bool))
{
cell.SetCellValue((bool)obj);
}
else
{
cell.SetCellValue(obj.ToString());
}
}