Office编程(一)C#读取Excel并显示出来,然后存入数据库
Execl导入数据库
直接从Excel中读取出来,然后对"供应商" select distinct,然后分别对每个供应商做表.
代码如下:
Code
1
2 protected void Page_Load(object sender, EventArgs e)
3 {
4 DataSet ds = ImportExcel(Server.MapPath("ExcelFile/供应商违约扣款.xls"));
5 GridView1.DataSource = ds.Tables["ExcelInfo"].DefaultView;
6 GridView1.DataBind();
7
8 ToDataBase(ds);
9 }
10
11 private DataSet ImportExcel(string strFileName)
12 {
13 if (strFileName == "") return null;
14 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
15 "Data Source=" + strFileName + ";" +
16 "Extended Properties=Excel 8.0;HDR=Yes;IMEX=1";
17 OleDbDataAdapter ExcelDA = new OleDbDataAdapter("SELECT trim(供应商) as 供应商,零件名称,型号,批量,下线数,下线率,不合格原因,考核原因,考核金额 FROM [Sheet1$]", strConn);
18 DataSet ExcelDs = new DataSet();
19 try
20 {
21 ExcelDA.Fill(ExcelDs, "ExcelInfo");
22
23 }
24 catch (Exception err)
25 {
26 System.Console.WriteLine(err.ToString());
27 }
28 return ExcelDs;
29 }
30
31
32 private bool ToDataBase(DataSet ds)
33 {
34 DataTable dtSupplier = new DataTable("dtSupplier");
35
36
37 DataView dv = ds.Tables[0].DefaultView;
38
39 string[] column = { "供应商" };
40 dtSupplier = dv.ToTable(true, column);
41
42 for (int i = 0; i < dtSupplier.Rows.Count; i++)
43 {
44
45 DataRow[] r = ds.Tables[0].Select("供应商='" + dtSupplier.Rows[i]["供应商"].ToString() + "'");
46
47 //插父表
48
49 for (int j = 0; j < r.Length; j++)
50 {
51 string ItemName = r[j]["零件名称"].ToString();
52 string scale = r[j]["型号"].ToString();
53 string batch = r[j]["批量"].ToString();
54 string downLine = r[j]["下线数"].ToString();
55 string downPercent = r[j]["下线率"].ToString();
56 string outReason = r[j]["不合格原因"].ToString();
57 string reason = r[j]["考核原因"].ToString();
58 string amt = r[j]["考核金额"].ToString();
59
60 //插子表
61 }
62
63 //save
64 }
65 return true;
66 }
1
2 protected void Page_Load(object sender, EventArgs e)
3 {
4 DataSet ds = ImportExcel(Server.MapPath("ExcelFile/供应商违约扣款.xls"));
5 GridView1.DataSource = ds.Tables["ExcelInfo"].DefaultView;
6 GridView1.DataBind();
7
8 ToDataBase(ds);
9 }
10
11 private DataSet ImportExcel(string strFileName)
12 {
13 if (strFileName == "") return null;
14 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
15 "Data Source=" + strFileName + ";" +
16 "Extended Properties=Excel 8.0;HDR=Yes;IMEX=1";
17 OleDbDataAdapter ExcelDA = new OleDbDataAdapter("SELECT trim(供应商) as 供应商,零件名称,型号,批量,下线数,下线率,不合格原因,考核原因,考核金额 FROM [Sheet1$]", strConn);
18 DataSet ExcelDs = new DataSet();
19 try
20 {
21 ExcelDA.Fill(ExcelDs, "ExcelInfo");
22
23 }
24 catch (Exception err)
25 {
26 System.Console.WriteLine(err.ToString());
27 }
28 return ExcelDs;
29 }
30
31
32 private bool ToDataBase(DataSet ds)
33 {
34 DataTable dtSupplier = new DataTable("dtSupplier");
35
36
37 DataView dv = ds.Tables[0].DefaultView;
38
39 string[] column = { "供应商" };
40 dtSupplier = dv.ToTable(true, column);
41
42 for (int i = 0; i < dtSupplier.Rows.Count; i++)
43 {
44
45 DataRow[] r = ds.Tables[0].Select("供应商='" + dtSupplier.Rows[i]["供应商"].ToString() + "'");
46
47 //插父表
48
49 for (int j = 0; j < r.Length; j++)
50 {
51 string ItemName = r[j]["零件名称"].ToString();
52 string scale = r[j]["型号"].ToString();
53 string batch = r[j]["批量"].ToString();
54 string downLine = r[j]["下线数"].ToString();
55 string downPercent = r[j]["下线率"].ToString();
56 string outReason = r[j]["不合格原因"].ToString();
57 string reason = r[j]["考核原因"].ToString();
58 string amt = r[j]["考核金额"].ToString();
59
60 //插子表
61 }
62
63 //save
64 }
65 return true;
66 }
这几天又要读excel, 回顾自己写的这个东西,问题很大条。
首先,IMEX不能解决所有的问题,当Jet Provider去扫描excel的列,最后决定了是什么类型以后,这个东西就不好使啦。
其次,select语句里面有hardcode,谁能保证每个excel里的表都叫做sheet1呢?
再有就是ToDataBase写的非常二,不知道当时怎么想的。。。
OK,全部改正。
首先,IMEX=1要写,但是要解决问题,还要进注册表:HKEY_LOCAL_MACHINE-->SOFTWARE-->Microsoft-->Jet-->4.0-->Engines-->Excel
修改里面的TypeGuessRows值为0,这个值决定了JET在扫描excel时要扫描多少行,为0时扫描全部,各位看官,如果excel特别大,设成0你就完了,哈哈
剩下的两条我改了代码:
Code
private static void ToDataBase(DataSet ds, string dbTableName)
{
string connectionString = "server=db-xp-pro;database=MountPleasant;uid=sa;pwd=;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string values = string.Empty;
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
if (i != ds.Tables[0].Columns.Count - 1)
{
values += "'" + dr[i].ToString().Replace("'", "''") + "'" + ",";
}
else
{
values += "'" + dr[i].ToString().Replace("'", "''") + "'";
}
}
string sql = "insert into [" + dbTableName + "] values(" + values + ")";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
private static DataSet ImportExcel(string strFileName)
{
if (strFileName.Length < 0) return null;
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
conn.Close();
IList<string> tblNames = new List<string>();
foreach (DataRow dr in dtSchema.Rows)
{
tblNames.Add((string)dr["TABLE_NAME"]);
}
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [" + tblNames[0] + "]", strConn);
DataSet ds = new DataSet();
try
{
adapter.Fill(ds);
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message.ToString());
System.Console.ReadLine();
}
return ds;
}
private static void ToDataBase(DataSet ds, string dbTableName)
{
string connectionString = "server=db-xp-pro;database=MountPleasant;uid=sa;pwd=;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string values = string.Empty;
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
if (i != ds.Tables[0].Columns.Count - 1)
{
values += "'" + dr[i].ToString().Replace("'", "''") + "'" + ",";
}
else
{
values += "'" + dr[i].ToString().Replace("'", "''") + "'";
}
}
string sql = "insert into [" + dbTableName + "] values(" + values + ")";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
private static DataSet ImportExcel(string strFileName)
{
if (strFileName.Length < 0) return null;
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
conn.Close();
IList<string> tblNames = new List<string>();
foreach (DataRow dr in dtSchema.Rows)
{
tblNames.Add((string)dr["TABLE_NAME"]);
}
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [" + tblNames[0] + "]", strConn);
DataSet ds = new DataSet();
try
{
adapter.Fill(ds);
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message.ToString());
System.Console.ReadLine();
}
return ds;
}
因为我的excel里只有一个sheet,所以我就硬编码1了,大家可以很容易扩展为多个sheet多个表。
本文着重解决excel导入数据库的问题,欢迎讨论。欢迎拍砖。
专注于企业级软件开发,做对
客户有用的软件。