最近在做将excel表的数据导出数据库,于是自己查了下资料方法介绍了很多种,尝试自己写了数据的查询的domel,写的比较简陋。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var path = @"C:\Users\Administrator\Desktop\test.xlsx";
dataGridView1.DataSource = null; //每次打开清空内容
DataTable dt = Getdata(path, "Sheet1").Tables[0];
///加载到dataGridView中
dataGridView1.DataSource = dt;
///获取所有的工作薄
List<string> tableName = GetTableName(path);
///DataTable转化成集合
IList<Man> users = ModelConvertHelper<Man>.ConvertToModel(dt);
}
/// <summary>
///连接数据源
/// </summary>
/// <returns></returns>
public OleDbConnection OleDbConnection(string path)
{
//判断文件后缀
string fileSuffix = System.IO.Path.GetExtension(path);
if (string.IsNullOrEmpty(fileSuffix))
return null;
string connString = "";
//判断Excel文件是2003版本还是2007版本
if (fileSuffix == ".xls")
connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
return conn;
}
/// <summary>
/// 读取数据源
/// </summary>
/// <param name="path">excel文件</param>
/// <param name="tableName">表名</param>
/// <returns></returns>
public DataSet Getdata(string path, string tableName)
{
OleDbConnection conn = OleDbConnection(path);
using (DataSet ds = new DataSet())
{
try
{
string sql_select = " SELECT * FROM" + "["+ tableName + "$]";
using (OleDbDataAdapter cmd = new OleDbDataAdapter(sql_select, conn))
{
cmd.Fill(ds);
conn.Close();
}
if (ds == null || ds.Tables.Count <= 0) return null;
}
catch (Exception ex)
{
Console.WriteLine("Getdata()", ex.Message);
}
return ds;
}
}
/// <summary>
/// 获取工作表名
/// </summary>
/// <param name="path">excel文件</param>
/// <returns></returns>
public List<string> GetTableName(string path)
{
List<string> tableName = new List<string>();
try
{
OleDbConnection conn = OleDbConnection(path);
DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
for (int i = 0; i < sheetNames.Rows.Count; i++)
{
DataRow row = sheetNames.Rows[i];
for (int j = 0; j < row.ItemArray.Length; j++)
{
var type = row.ItemArray[j].GetType().Name;
if (type != "DBNull")
{
string name = Convert.ToString(row.ItemArray[j]);
if (name.EndsWith("$"))
{
tableName.Add(name);
}
}
}
}
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine("GetTableName()", ex.Message);
}
return tableName;
}
public class ModelConvertHelper<T> where T : new() // 此处一定要加上new()
{
public static IList<T> ConvertToModel(DataTable dt)
{
IList<T> ts = new List<T>();// 定义集合
Type type = typeof(T); // 获得此模型的类型
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
// 检查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
};
ts.Add(t);
}
return ts;
}
}
}
public class Man
{
public double Id { get; set; }
public string Name { get; set; }
public double Age { get; set; }
}
}