方法如下:
参数:exvelPath :文件路径 sheetName :文件Sheet名
(CSV文件的Sheet名与文件名是一样的,可通过 Path.GetFileNameWithoutExtension(exvelPath ) 方法直接获取到)
public static System.Data.DataTable Read2DataTable(string exvelPath,string sheetName)
{
object missing = System.Reflection.Missing.Value;
Application excel = new ApplicationClass();
if (excel == null)
{
return null;
}
System.Data.DataTable dt = new System.Data.DataTable();
excel.Visible = false;
Workbook wb = excel.Application.Workbooks.Open(exvelPath);
Worksheet ws = wb.Worksheets[sheetName] as Microsoft.Office.Interop.Excel.Worksheet;
try
{
for (int cd = 1; cd <= ws.UsedRange.Columns.Count; cd++)
{
if (!dt.Columns.Contains(ws.Cells[1, cd].ToString()))
{
dt.Columns.Add(((Range)ws.Cells[1, cd]).Value.ToString());
}
}
for (int c = 1; c <= ws.UsedRange.Columns.Count; c++)
{
for (int i = 0; i < ws.UsedRange.Rows.Count; ++i)
{
if (i != ws.UsedRange.Rows.Count)
{
string cValue = ((Range)ws.Cells[i + 2, c]).Text.ToString().Trim();
if (cValue == "" || cValue is null)
{
cValue = "";
}
if (dt.Rows.Count == ws.UsedRange.Rows.Count)
{
dt.Rows[i][dt.Columns[c - 1].ColumnName] = cValue;
}
else
{
DataRow dr = dt.NewRow();
dr[dt.Columns[c - 1].ColumnName] = cValue;
dt.Rows.Add(dr);
}
}
}
}
}
catch (Exception)
{
throw;
}
finally
{
wb.Close();
excel.Quit();
excel = null;
}
return dt;
}
顺便可以看看如何将DateTable数据导出到CSV文件中 这篇文章