c#大圣之路笔记——c#通过页面把excel中的数据导入到DB中(全部)

  1 ///html
  2 
  3 
  4 <html xmlns="http://www.w3.org/1999/xhtml">
  5 <head id="Head1" runat="server">
  6     <title> 批量修改</title>
  7     <link href="../css/main.css" rel="stylesheet" type="text/css" />
  8     <link href="../css/Styles_1.css" rel="stylesheet" type="text/css" />
  9     <script type="text/javascript">
 10 
 11 
 12         function ShowWaiting() {
 13             document.getElementById('doing').style.visibility = 'visible';
 14         }
 15         function CloseWaiting() {
 16             document.getElementById('doing').style.visibility = 'hidden';
 17         }
 18         function MyOnload() {
 19             document.getElementById('doing').style.visibility = 'hidden';
 20         }
 21 
 22         if (window.onload == null) {
 23             window.onload = MyOnload;
 24         }
 25     
 26     </script>
 27 
 28 </head>
 29 <body ms_positioning="GridLayout">
 30     <form id="form1" runat="server" method="post">
 31         <table width="99%">
 32         <tr>
 33             <td style="height:30px">
 34                 <b> 批量修改</b>
 35             </td>
 36         </tr>
 37         <tr class="SpliteLine" style="height:1px">
 38             <td style="background-color:#0071C5"></td>
 39         </tr>
 40         <tr>
 41             <td>
 42                 <input  type="file" id="myFile" name="myFile" runat="server" class="btnUpload" size="46" style="border:1px solid #ccc" />
 43                 <asp:Button ID="btnUpload" Text="上传数据" runat="server" CssClass="ButtonCommand" style="height:24px; 60px;" OnClick="btnUpload_Click" />
 44             </td>
 45         </tr>
 46         <tr class="SpliteLine" style="height:1px"> 
 47             <td style="background-color:#0071C5"></td> 
 48         </tr>
 49         <tr align="right">
 50             <td>
 51             <asp:Button ID="btnExport" runat="server" Text ="导出错误数据" CssClass="ButtonCommand" OnClick="btnExport_Click" style="height:24px; 100px;"/>
 52             </td>
 53         </tr>
 54         <tr>
 55             <td>错误数据有:<asp:Label ID="errData" runat="server"></asp:Label>条。</td>
 56         </tr>
 57         <tr>
 58             <td>
 59                 <asp:DataGrid ID="GridMain" runat="server" Width="99%" 
 60                     AutoGenerateColumns="false"  AllowPaging="true" PageSize="20" 
 61                     AllowSorting="true" DataMember=""  AlternatingItemStyle-BackColor="#EBE9E9" 
 62                     OnPageIndexChanged="GridMain_PageIndexChanged" 
 63         onselectedindexchanged="GridMain_SelectedIndexChanged"> 
 64                 <AlternatingItemStyle CssClass="datagridAlternating" />
 65                 <HeaderStyle CssClass="tableHead" Height="22" />
 66                 <Columns>
 67                     <asp:BoundColumn DataField="errorMsg" HeaderText="错误原因">
 68                     <ItemStyle HorizontalAlign="Center" Width="25%" />
 69                     </asp:BoundColumn>
 70                       <asp:BoundColumn DataField="stor_id" HeaderText=" Store ID">
 71                     <ItemStyle HorizontalAlign="Center" Width="25%" />
 72                     </asp:BoundColumn>
 73                       <asp:BoundColumn DataField="slsprs_id" HeaderText="SR ID">
 74                     <ItemStyle HorizontalAlign="Center" Width="25%" />
 75                     </asp:BoundColumn>
 76                      <asp:BoundColumn DataField="slsprs_nm" HeaderText="SR NM">
 77                     <ItemStyle HorizontalAlign="Center" Width="25%" />
 78                     </asp:BoundColumn> 
 79                 </Columns>
 80                 <PagerStyle  Position="Top" Mode="NumericPages"/>
 81                 </asp:DataGrid>
 82             </td>
 83         </tr>
 84         </table> 
 85     <div>
 86     
 87 
 88     </div>
 89     </form>
 90     <div id='doing' style='z-index: 12000; left: 0px;  100%; cursor: wait; position: absolute;   top: 0px; height: 100%; filter: alpha(opacity=45); opacity: 0.5; color: #000000;  background-color: #FFFFFF;'>
 91         <table width='100%' height='100%' id="Table2">
 92             <tr align='center' valign='middle'>
 93                 <td>
 94                     <table id="Table3" class="loading">
 95                         <tr align='center' valign='middle'>
 96                             <td>
 97                                 <img src="../Images/Waitting.gif" />
 98                             </td>
 99                              <td>&nbsp;&nbsp;</td>
100                             <td valign="middle">
101                                 <span id=txtLoading0 style="font-size:14px; color: #800080; font-weight: bold;">页面正在加载数据,请稍候...</span>
102                                <br><span id=txtLoading1 style="font-size:14px; color: #800080;">Loading,please wait...</span>
103                             </td>
104                         </tr>
105                     </table>
106                 </td>
107             </tr>
108         </table>
109     </div>
110  
111 </body>
112 </html>




  1 ///c# 
  2 
  3 
  4 using System;
  5 using System.Collections.Generic;
  6 using System.Linq;
  7 using System.Web;
  8 using System.Web.UI;
  9 using System.Web.UI.WebControls;
 10 using System.IO;
 11 using CompIntelligenceWeb.User;
 12 
 13 using System.Data.OleDb;
 14 using System.Data;
 15 using System.Data.SqlClient;
 16 using System.Text;
 17 using Microsoft.ApplicationBlocks.Data;
 18 
 19 namespace PRCSales_external.Store
 20 {
 21     public partial class XoemStoreSR_AsignUpdate : PageBase
 22     {
 23         protected OleDbConnection xlconn;
 24         protected OleDbDataAdapter xlda;
 25         protected DataTable Err_dt;
 26         protected string tableName;
 27         protected string WWID;
 28 
 29         public string connString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
 30 
 31         protected void Page_Load(object sender, EventArgs e)
 32         {
 33             this.btnUpload.Attributes.Add("onclick", "ShowWaiting();");
 34             if (!IsPostBack)
 35             {
 36                 WWID = ((AccessControler)this.Session["_accessctrl"]).GetWWID();
 37 
 38                 initTable();
 39                 bindNextPage(0);
 40             }
 41             tableName = ViewState["TableName"].ToString();
 42             Err_dt = (DataTable)ViewState["table"];
 43 
 44         }
 45 
 46         private void bindNextPage(int p)
 47         {
 48             tableName = ViewState["TableName"].ToString();
 49             Err_dt = (DataTable)ViewState["table"];
 50             if (ViewState["Sort"].ToString() != "")
 51             {
 52                 DataView dv = new DataView(Err_dt);
 53                 dv.Sort = ViewState["Sort"].ToString();
 54                 GridMain.DataSource = dv;
 55             }
 56             else
 57             {
 58                 GridMain.DataSource = Err_dt;
 59             }
 60             GridMain.CurrentPageIndex = p;
 61             GridMain.DataBind();
 62         }
 63 
 64         protected void GridMain_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
 65         {
 66             currentPageIndex = e.NewPageIndex;
 67             this.GridMain.CurrentPageIndex = currentPageIndex;
 68             GridMain.DataSource = Err_dt;
 69             GridMain.DataBind();
 70         }
 71 
 72         protected int currentPageIndex
 73         {
 74             set
 75             {
 76                 ViewState["currentPageIndex"] = value;
 77             }
 78             get
 79             {
 80                 if (ViewState["currentPageIndex"] != null)
 81                 {
 82                     return int.Parse(ViewState["currentPageIndex"].ToString());
 83                 }
 84                 else
 85                 {
 86                     return 0;
 87                 }
 88             }
 89         }
 90 
 91 
 92         private void initTable()
 93         {
 94             tableName = "XoemStoreSR_AsignUpdate" + DateTime.UtcNow.ToString();
 95             Err_dt = new DataTable(tableName);
 96             ViewState["TableName"] = tableName;
 97             ViewState["table"] = Err_dt;
 98             ViewState["Sort"] = "";
 99         }
100         /// <summary>
101         /// 通过excel导入数据进入临时物理表
102         /// </summary>
103         /// <param name="sender"></param>
104         /// <param name="e"></param>
105         protected void btnUpload_Click(object sender, EventArgs e)
106         {
107             if (this.myFile.PostedFile.FileName.Trim() == "")
108             {
109                 string msg = "请选择文件";
110                 Response.Write("<script type='text/javascript'> alert('" + msg + "');</script>");
111                 return;
112             }
113             //验证文件格式
114             string ext = this.myFile.PostedFile.FileName.Substring(this.myFile.PostedFile.FileName.LastIndexOf(".")).ToLower();
115             if (ext != ".xls" && ext != ".xlsx")
116             {
117                 string msg = "文件格式错误!";
118                 this.PageAlert(msg);
119                 return;
120             }
121             if (!Directory.Exists(Server.MapPath("upload")))
122             {
123                 Directory.CreateDirectory(Server.MapPath("upload"));
124             }
125             //文件路径
126             string aFile = this.myFile.PostedFile.FileName.ToString();
127             //文件名
128             string aFirstName = aFile.Substring(aFile.LastIndexOf("\") + 1, (aFile.LastIndexOf(".") - aFile.LastIndexOf("\") - 1));
129 
130             string fileNO = System.DateTime.Now.Year.ToString("00") + System.DateTime.Now.Month.ToString("00") + System.DateTime.Now.Day.ToString("00") + System.DateTime.Now.Hour.ToString("00") + System.DateTime.Now.Minute.ToString("00") + System.DateTime.Now.Second.ToString("00") + "_" + WWID;
131 
132 
133             //临时存放
134             string sFileSavePath = Server.MapPath("upload") + "\" + fileNO + ext;
135             //保存文件
136             this.myFile.PostedFile.SaveAs(sFileSavePath);
137             DataSet dt = new DataSet();
138             try
139             {
140                 if (ext == ".xls")
141                 {
142                     xlconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + sFileSavePath + "';Extended Properties="Excel 8.0;HDR=YES;IMEX=1"");
143                 }
144                 else
145                 {
146                     xlconn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + sFileSavePath + "';Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1"");
147                 }
148             }
149             catch (Exception ex)
150             {
151                 this.PageAlert(ex.Message);
152                 return;
153             }
154             string sheetName = "店面SR模板";
155             try
156             {
157                 //获取数据保存到DataSet
158                 xlda = new OleDbDataAdapter("select * from [" + sheetName + "$]", xlconn);
159                 xlda.Fill(dt);
160             }
161             catch
162             {
163                 Response.Write("<script type='text/javascript'> alert('请核对模板是否正确!');</script>");
164                 errData.Text = "";
165                 return;
166             }
167             finally
168             {
169                 xlconn.Close();
170                 xlda.Dispose();
171             }
172             SqlConnection conn = new SqlConnection(connString);
173             SqlCommand cmd = new SqlCommand();
174             cmd.CommandType = CommandType.Text;
175             cmd.Connection = conn;
176 
177 
178             try
179             {
180                 int count = dt.Tables[0].Rows.Count;
181                 int number = 1;
182                 if (CheckTemplate(dt.Tables[0]))
183                 {
184                     StringBuilder sql = new StringBuilder();
185                     sql.Append("set NOCOUNT ON" + "
");
186                     sql.Append("INSERT INTO prc_xoem_stor_sr_data_raw (stor_id,slsprs_id,slsprs_nm,lst_upt_dtm) 
");
187 
188                     foreach (DataRow dr in dt.Tables[0].Rows)
189                     {
190                         string stor_id = "'" + dr[0].ToString().Trim() + "'";
191                         string slsprs_id = "'" + dr[1].ToString().Trim() + "'";
192                         string slsprs_nm = "'" + dr[2].ToString().Trim() + "'";
193                         string upload_tm = "'" + DateTime.Now.ToString("yyyy-MM-dd") + "'";
194 
195                       
196 
197                         if (number == count)
198                         {
199                             sql.Append("select" + stor_id + "," + slsprs_id + "," + slsprs_nm + "," + upload_tm + "
");
200                         }
201                         else
202                         {
203                             sql.Append("select" + stor_id + "," + slsprs_id + "," + slsprs_nm + "," + upload_tm + "UNION ALL" + "
");
204                         }
205                        
206 
207                         number++;
208                     }
209                     sql.Append("set NOCOUNT OFF" + "
");
210                     conn.Open();
211                     cmd.CommandTimeout = 300;
212                     cmd.CommandText = sql.ToString();
213                     cmd.ExecuteNonQuery();
214                 }
215                 else
216                 {
217                     this.PageAlert("上传失败");
218                     errData.Text = "";
219                     return;
220                 }
221             }
222             catch (Exception ex)
223             {
224                 this.PageAlert(ex.Message);
225                 return;
226             }
227             finally
228             {
229                 conn.Close();
230                 cmd.Dispose();
231             }
232 
233             //执行脚本导入数
234             ExcuteProcedure();
235 
236             //返回错误数据
237             BindERData();
238 
239             //防止缓存
240             //Session.Remove(tableName);
241             ViewState["table"] = null;
242             ViewState["table"] = Err_dt;
243 
244             if (Err_dt != null)
245             {
246                 errData.Text = string.Format("{0}", int.Parse(Err_dt.Rows.Count.ToString()));
247             }
248             else
249             {
250                 errData.Text = string.Format("{0}", 0);
251             }
252 
253             int successCount = dt.Tables[0].Rows.Count - Err_dt.Rows.Count;
254             this.PageAlert("更新成功" + successCount + "条,失败" + errData.Text + "条。");
255 
256 
257 
258 
259         }
260 
261         private void BindERData()
262         {
263             SqlConnection conn = new SqlConnection(connString);
264             StringBuilder sql = new StringBuilder();
265             sql.Append("select a.Category+':'+a.Remark as errorMsg, b.*   INTO #stor_sr  FROM prc_xoem_stor_sr_data_log a");
266             sql.Append(" INNER JOIN prc_xoem_stor_sr_data_raw b ON a.data_id=b.id  WHERE a.errorFlag=0 AND a.Category='导入失败'");
267             sql.Append(" UPDATE prc_xoem_stor_sr_data_log  SET errorFlag=1  WHERE Category='导入失败'");
268             sql.Append(" SELECT * FROM #stor_sr");
269             try
270             {
271                 conn.Open();
272                 Err_dt = SqlHelper.ExecuteDataset(conn, CommandType.Text, sql.ToString()).Tables[0];
273                 GridMain.DataSource = Err_dt;
274                 GridMain.DataBind();
275             }
276             catch (Exception ex)
277             {
278                 this.PageAlert(ex.Message);
279                 Err_dt = null;
280                 GridMain.DataSource = Err_dt;
281                 GridMain.DataBind();
282             }
283             finally
284             {
285                 conn.Close();
286             }
287 
288         }
289         /// <summary>
290         /// 执行更新店面SR
291         /// </summary>
292         private void ExcuteProcedure()
293         {
294             SqlConnection conn = new SqlConnection(connString);
295             SqlCommand cmd = new SqlCommand();
296             cmd.CommandTimeout = 6000000;
297             cmd.CommandText = "prc_xoem_stor_sr_update";
298             cmd.CommandType = CommandType.StoredProcedure;
299             cmd.Connection = conn;
300 
301             string update_dtm = DateTime.Now.ToString("yyyy-MM-dd");
302             try
303             {
304                 cmd.Parameters.AddWithValue("@yyyydd", update_dtm);
305                 conn.Open();
306                 cmd.ExecuteNonQuery();
307             }
308             catch (Exception ex)
309             {
310                 this.PageAlert(ex.Message);
311             }
312             finally
313             {
314                 conn.Close();
315                 cmd.Dispose();
316             }
317 
318 
319         }
320         /// <summary>
321         /// 验证模板列名是否正确
322         /// </summary>
323         /// <param name="dataTable"></param>
324         /// <returns></returns>
325         private bool CheckTemplate(DataTable dt)
326         {
327             bool boolResult = true;
328             string msg = string.Empty;
329             List<string> list = new List<string>();
330             for (int i = 0; i < dt.Columns.Count; i++)
331             {
332                 list.Add(dt.Columns[i].ColumnName);
333             }
334             try
335             {
336                 if (list[0].ToString().Trim() != "Store ID")
337                 {
338                     msg = "第 A 列应该为: Store ID";
339                     this.PageAlert(msg);
340                     boolResult = false;
341                 }
342                 if (list[1].ToString().Trim() != "SR ID")
343                 {
344                     msg = "第 B 列应该为:SR ID";
345                     this.PageAlert(msg);
346                     boolResult = false;
347                 }
348                 if (list[2].ToString().Trim() != "SR Name")
349                 {
350                     msg = "第 C 列应该为:SR Name";
351                     this.PageAlert(msg);
352                     boolResult = false;
353                 }
354             }
355             catch
356             {
357                 this.PageAlert("请核对模板是否正确");
358                 boolResult = false;
359             }
360             return boolResult;
361         }
362 
363 
364         protected void btnExport_Click(object sender, EventArgs e)
365         {
366             GridMain.AllowPaging = false;
367             GridMain.AllowSorting = false;
368 
369             bindNextPage(0);
370 
371             Export(GridMain, "StoreSRErrorList.xls", "StoreSRErrorList", "application/ms-excel");
372 
373             GridMain.AllowPaging = true;
374             GridMain.AllowSorting = false;
375 
376         }
377 
378         #region  Export to the excel
379 
380 
381         // Export to the excel
382         private void Export(System.Web.UI.WebControls.DataGrid dg, string fileName, string fn, string typeName)
383         {
384             System.Web.HttpResponse httpResponse = Page.Response;
385             httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
386             httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
387             httpResponse.ContentType = typeName;
388             System.IO.StringWriter tw = new System.IO.StringWriter();
389             System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
390             dg.RenderControl(hw);
391 
392             //httpResponse.Write(tw.ToString());
393             //httpResponse.End();
394             string filePath = Server.MapPath("..") + fn + DateTime.Now.Ticks.ToString() + new Random().Next(100).ToString();
395             System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
396             sw.Write(tw.ToString());
397             sw.Close();
398             DownFile(httpResponse, fileName, filePath);
399 
400             httpResponse.End();
401         }
402 
403         private bool DownFile(System.Web.HttpResponse Response, string fileName, string fullPath)
404         {
405             System.IO.FileStream fs = System.IO.File.OpenRead(fullPath);
406             try
407             {
408                 Response.ContentType = "application/octet-stream";
409 
410                 Response.AppendHeader("Content-Disposition", "attachment;filename=" +
411                 HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312");
412                 //System.IO.FileStream fs = System.IO.File.OpenRead(fullPath);
413                 long fLen = fs.Length;
414                 int size = 102400;//每100K同时下载数据
415                 byte[] readData = new byte[size];//指定缓冲区的大小
416                 if (size > fLen) size = Convert.ToInt32(fLen);
417                 long fPos = 0;
418                 bool isEnd = false;
419                 while (!isEnd)
420                 {
421                     if ((fPos + size) > fLen)
422                     {
423                         size = Convert.ToInt32(fLen - fPos);
424                         readData = new byte[size];
425                         isEnd = true;
426                     }
427                     fs.Read(readData, 0, size);//读入一个压缩块
428                     Response.BinaryWrite(readData);
429                     fPos += size;
430                 }
431                 fs.Close();
432                 FileInfo FI = new FileInfo(fullPath);
433                 if (FI.Exists)
434                 {
435                     FI.Delete();
436                 }
437                 return true;
438             }
439             catch
440             {
441                 return false;
442             }
443             finally
444             {
445                 fs.Close();
446             }
447         }
448 
449         #endregion
450 
451 
452 
453         /// <summary>
454         /// 提示代码
455         /// </summary>
456         /// <param name="msg"></param>
457         private void PageAlert(string msg)
458         {
459             this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script type='text/javascript'> alert('" + msg + "') </script>");
460         }
461 
462         protected void GridMain_SelectedIndexChanged(object sender, EventArgs e)
463         {
464 
465         }
466 
467 
468     }
469 }


 
原文地址:https://www.cnblogs.com/allenzhang/p/5454679.html