在开发过程中我们经常会用到excel的操作,这篇文章来讲解读取excel表格,
导出的文章可以查看我另一篇博客https://blog.csdn.net/qq_39569480/article/details/104426928
1.第一种方式 文件流读取到datatable中
public DataTable Getcsv表格(string path)
{
return csv2dt(path, 0);
}
/// <summary>
/// 将Csv读入DataTable
/// </summary>
/// <param name="filePath">csv文件路径</param>
/// <param name="n">表示第n行是字段title,第n+1行是记录开始</param>
/// <param name="k">可选参数表示最后K行不算记录默认0</param>
public DataTable csv2dt(string filePath, int n)
{
DataTable dt = new DataTable();
String csvSplitBy = "(?<=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)";
StreamReader reader = new StreamReader(filePath, System.Text.Encoding.Default, false);
//StreamReader reader = new StreamReader(filePath, System.Text.Encoding.Unicode, false);如果出现乱码多换几种编码方式试一下
int i = 0, m = 0;
reader.Peek();
while (reader.Peek() > 0)
{
m = m + 1;
string str = reader.ReadLine();
if (m >= n + 1)
{
if (m == n + 1) //如果是字段行,则自动加入字段。
{
MatchCollection mcs = Regex.Matches(str, csvSplitBy);
foreach (Match mc in mcs)
{
dt.Columns.Add(mc.Value); //增加列标题
}
}
else
{
MatchCollection mcs = Regex.Matches(str, "(?<=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)");
i = 0;
System.Data.DataRow dr = dt.NewRow();
foreach (Match mc in mcs)
{
dr[i] = mc.Value;
i++;
}
dt.Rows.Add(dr); //DataTable 增加一行
}
}
}
return dt;
}
2.第二种方式 操作数据库的方式写查询语句
OLEDB的Excel的IMEX和HDR是什么意思?
Extended Properties=""Excel 8.0;HDR=yes;IMEX=1""
A: HDR ( HeaDer Row )设置
若指定值为Yes,代表 Excel 档中的工作表第一行是栏位名称
若指定值为 No,代表 Excel 档中的工作表第一行就是资料了,没有栏位名称
B:IMEX ( IMport EXport mode )设置
IMEX 有三种模式,各自引起的读写行动也不合,容后再述:
0 is Export mode
1 is Import mode
2 is Linked mode (full capabilities)
我这里希罕要申明的就是 IMEX 参数了,因为不合的模式代表著不合的读写行动:
当 IMEX=0 时为“汇出模式”,这个模式开启的 Excel 档案只能用来做“写入”用处。
当 IMEX=1 时为“汇入模式”,这个模式开启的 Excel 档案只能用来做“读取”用处。
当 IMEX=2 时为“连结模式”,这个模式开启的 Excel 档案可同时增援“读取”与“写入”用处。
所谓“4.5010763038+14 ”只是显示用的,实际还是“450107630382345”。所以使用读取即 IMEX=1时,得到“4.5010763038+14 ”。
而 IMEX=0时,得到“450107630382345”。
单独读取csv文件方式(如果是csv格式要在csv同级目录创建一个ini文件,不然读不完整列)
ini文件内容
[a.csv]//文件名
Format=TabDelimited
ColNameHeader=True
MaxScanRows=0
#Col1=OrderID Text Width 10 这两列可以指定读取那些列 这里不需要不写这两列则读取全部列
#Col2=OrderName Text Width 30
[DllImport("kernel32")]
public static extern long WritePrivateProfileString(string section, string key, string value, string iniPath);
string fileName = csvPath.Replace(csvPath.Remove(csvPath.LastIndexOf("\\") + 1), "");
WritePrivateProfileString(fileName, "Format", "TabDelimited", csvPath.Remove(csvPath.LastIndexOf("\\") + 1) + @"\Schema.ini");
WritePrivateProfileString(fileName, "ColNameHeader", "True", csvPath.Remove(csvPath.LastIndexOf("\\") + 1) + @"\Schema.ini");
WritePrivateProfileString(fileName, "MaxScanRows", "0", csvPath.Remove(csvPath.LastIndexOf("\\") + 1) + @"\Schema.ini");
DateTable dt = CsvReader(fileName, csvPath);//文件名 路径
帮助类读取csv文件
/// <summary>
/// 读取Csv文件返回DataSet
/// </summary>
/// <param name="sql">查询语句 </param>
/// <param name="FilePath">文件路径 </param>
/// <returns>Csv内容</returns>
public DataTable CsvReader(string fileName,string FilePath)
{
DataSet CsvData = new DataSet();
DataTable dt = new DataTable();
string strConnCSV = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath.Remove(FilePath.LastIndexOf("\\") + 1) + ";Extended Properties='TEXT;IMEX=1;HDR=Yes;FMT=Delimited;CharacterSet=UNICODE;'";
System.Data.OleDb.OleDbConnection objConn = new OleDbConnection(strConnCSV);
objConn.Open();
string strSql = "SELECT * FROM " + fileName;
System.Data.OleDb.OleDbDataAdapter odbcCSVDataAdapter = new OleDbDataAdapter(strSql, strConnCSV);
odbcCSVDataAdapter.Fill(dt);
return dt;
}
调用方法
DataTable dt = ToDataSet(Path); //
帮助类读取excel文件(.xls .xlsx)
//数据返回到DataSet
internal DataSet ToDataSet(string filePath)
{
string fileType = System.IO.Path.GetExtension(filePath);
if (string.IsNullOrEmpty(fileType)) return null;
if (fileType.ToLower() == ".xls")
{
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";
}
else if (fileType.ToLower() == ".xlsx")
{
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;\"";
}
else if (fileType.ToLower() == ".csv")
{
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath.Remove(filePath.LastIndexOf("\\") + 1) + ";Extended Properties='Text;FMT=Delimited;HDR=YES;'";
}
else {
MessageBox.Show("文件格式不不符合要求,此系统只支持导入xls,xlsx,csv 三种格式,详情咨询软件供应商");
}
string sql_F = "Select * FROM [{0}]";
OleDbConnection conn = new OleDbConnection ();
OleDbDataAdapter da = null;
DataTable dtSheetName = null;
DataSet ds = new DataSet();
try
{
conn.ConnectionString=connStr;
conn.Open();
string SheetName = "";
dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
da = new OleDbDataAdapter();
for (int i = 0; i < dtSheetName.Rows.Count; i++)
{
SheetName = Convert.ToString(dtSheetName.Rows[i]["TABLE_NAME"]);
if (SheetName.Contains("$") && !SheetName.Replace("'", "").EndsWith("$"))
{
continue;
}
da.SelectCommand = new OleDbCommand(String.Format(sql_F, SheetName), conn);
DataSet dsItem = new DataSet();
da.Fill(ds, "Mdt1");
DataTable table = ds.Tables["Mdt1"];
DataRow row = table.NewRow();
da.Update(ds, "Mdt1");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
// 关闭连接
if (conn.State == ConnectionState.Open)
{
conn.Close();
da.Dispose();
conn.Dispose();
}
}
return ds;
}