1 // block copy to DB from Excel
2 //By xijun,
3 //step 1 create an excel file C:\Inetpub\wwwroot\test.xls , fill cell(1,1) with "Data",cell(1,2) with "name"
4 //step 2 create table named "Data" with 2 column ("data","name") in your DB
5 //there the code below:
6 DateTime t1 = DateTime.Now;
7 Response.Write("<br>start time:" + t1.ToString());
8 string ExcelFile = @"C:\\20090916_Hub_Report.xls";
9 string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFile + ";Extended Properties=‘Excel 8.0;HDR=YES;IMEX=1‘";
10
11 using (OleDbConnection excelConnection = new OleDbConnection(excelConnectionString))
12 {
13
14 excelConnection.Open();
15 //Getting source data
16 //非空讀入數據
17 OleDbCommand command = new OleDbCommand("Select [Region],[CustomerPN],[RMA],[Date],[QTY],[Return/Pull] FROM [20090916_Hub_Report$] ", excelConnection);
18 // Initialize SqlBulkCopy object
19
20 using (OleDbDataReader dr = command.ExecuteReader())
21 {
22 // Copy data to destination
23 string sqlConnectionString = @"Data Source=MININT-G87PHNA\SQLEXPRESS;Initial Catalog=GDS_Service;Integrated Security=True";
24 using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
25 {
26 bulkCopy.DestinationTableName = "GDS_Hub_data";
27 //加入只加入一個列的話,那么就會其他數據庫列都默認為空。
28 bulkCopy.ColumnMappings.Add("Region", "region");
29 bulkCopy.ColumnMappings.Add("CustomerPN", "customer_item_number");
30 bulkCopy.ColumnMappings.Add("RMA", "Rma");
31 bulkCopy.ColumnMappings.Add("Date", "date");
32 bulkCopy.ColumnMappings.Add("QTY", "Qty_1");
33 bulkCopy.ColumnMappings.Add("Return/Pull", "return_pull");
34 //bcp.BatchSize = 100;//每次传输的行数
35 //bcp.NotifyAfter = 100;//进度提示的行数
36 bulkCopy.BatchSize = 100;
37 bulkCopy.NotifyAfter = 100;
38 bulkCopy.WriteToServer((IDataReader)dr);
39 40 41 }