码迷,mamicode.com
首页 > Windows程序 > 详细

C#Excel导出,导入操作

时间:2015-11-04 13:01:15      阅读:346      评论:0      收藏:0      [点我收藏+]

标签:

1.我们在开发操作中,经常会用到Excel操作,其中包括,Excel导入,Excel导出,附件的上传,下载,包括Excel动态导入,我们这里就不讲,主要讲Excel导入,导出操作,而动态的操作,只需要在原来基础上做修改即可。需求图:

   技术分享

2.具体代码实现:

  A:Excel导出,其中会因为Excel版本的不同导致导出的成败效果不同,具体情况具体分析解决:

    

 1    #region//导出数据
 2     /// <summary>
 3     /// /导单
 4     /// </summary>
 5     /// <param name="sender"></param>
 6     /// <param name="e"></param>
 7     protected void BtExcelOut_Click1(object sender, EventArgs e)
 8     {
 9         DataTable dt = getDt();
10         if (dt == null || dt.Rows.Count == 0)
11         {
12             Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert(‘没有内容!‘)</script>", false);
13             return;
14         }
15         CreateExcel(dt, "DSR已选中社群");
16     }
17     /// <summary>
18     /// 获取筛选数据
19     /// </summary>
20     /// <returns></returns>
21     public DataTable getDt()
22     {
23         SqlConnection conn = SqlHelperEx.ConnOpen("SPSDB");
24         DataTable dt = new DataTable();
25         string lists = Request["itemList"];
26         string[] ids = lists.Split(,);
27         if (ids.Length > 0 && lists != "")
28         {
29             string strlist = "";
30             for (int k = 0; k < ids.Length; k++)
31             {
32                 strlist += ids[k].ToString() + ",";
33             }
34             if (strlist != "" && strlist != null) strlist = strlist.Substring(0, strlist.Length - 1);
35             string strsql = "SELECT (CASE classID WHEN 1 THEN ‘论坛‘ WHEN 2 THEN ‘微信‘ WHEN 3 THEN ‘微博‘  WHEN 4 THEN ‘朋友圈‘  WHEN 5 THEN ‘QQ群‘  ELSE ‘其他‘ END)AS [类型] ,(CASE CategoryID WHEN 1 THEN ‘家具‘ WHEN 2 THEN ‘电商‘ WHEN 3 THEN ‘SNS媒体‘ ELSE ‘其它‘ END) AS [分类] , SNSName AS [网站] ,accountID AS [板块],URL AS [链接], Area AS [地域], fans AS [粉丝(关注)数],IsTiop AS [置顶/天],highlight AS [加精/周], Stars AS [星级], LinkWay AS [直接联系方式],media AS [媒介],SNSContact AS [媒介联系方式] FROM   BaseSNSInfo WHERE IsValid=1 AND classID=1  AND ID  in (" + strlist + ")";
36             dt = SqlHelperEx.GetDataTable(strsql, conn);
37             SqlHelperEx.ConnClose(conn);
38         }
39         else
40         {
41             string strsql = "SELECT (CASE classID WHEN 1 THEN ‘论坛‘ WHEN 2 THEN ‘微信‘ WHEN 3 THEN ‘微博‘  WHEN 4 THEN ‘朋友圈‘  WHEN 5 THEN ‘QQ群‘  ELSE ‘其他‘ END)AS [类型] ,(CASE CategoryID WHEN 1 THEN ‘家具‘ WHEN 2 THEN ‘电商‘ WHEN 3 THEN ‘SNS媒体‘ ELSE ‘其它‘ END) AS [分类] , SNSName AS [网站] ,accountID AS [板块],URL AS [链接], Area AS [地域], fans AS [粉丝(关注)数],IsTiop AS [置顶/天],highlight AS [加精/周], Stars AS [星级], LinkWay AS [直接联系方式],media AS [媒介],SNSContact AS [媒介联系方式] FROM   BaseSNSInfo WHERE IsValid=1 AND classID=1";
42             dt = SqlHelperEx.GetDataTable(strsql, conn);
43             SqlHelperEx.ConnClose(conn);
44         }
45         return dt;
46     }
47     //<summary>
48     //导出到EXcel
49     //</summary>
50     //<param name="dt"></param>
51     //<param name="FileName"></param>
52     public void CreateExcel(DataTable dt, string FileName)
53     {
54         Response.Clear();
55         Response.Charset = "GB2312";
56         Response.ContentEncoding = Encoding.Default;
57         Response.Buffer = true;
58         Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
59         Response.ContentType = "application/ms-excel";
60         string colHeaders = string.Empty;
61         string ls_item = string.Empty;
62         DataRow[] myRow = dt.Select();
63         int i = 0;
64         int cl = dt.Columns.Count;
65         for (int k = 0; k < dt.Columns.Count; k++)
66         {
67             if (k == (dt.Columns.Count - 1))
68             {
69                 colHeaders += dt.Columns[k].ToString() + "\n";
70             }
71             else
72             {
73                 colHeaders += dt.Columns[k].ToString() + "\t";
74             }
75         }
76         Response.Output.Write(colHeaders);
77         foreach (DataRow row in myRow)
78         {
79             for (i = 0; i < cl; i++)
80             {
81                 if (i == (cl - 1))
82                 {
83                     ls_item += row[i].ToString() + "\n";
84                 }
85                 else
86                 {
87                     ls_item += row[i].ToString() + "\t";
88                 }
89             }
90             Response.Output.Write(ls_item);
91             ls_item = string.Empty;
92         }
93         Response.Output.Flush();
94         Response.End();
95     }
96     #endregion

3.Excel导入功能,有动态的导入,同时Excel版本也有不同,也会导致导入效果,具体情况具体分析解决:

   

  1  #region 导入数据
  2 
  3     /// <summary>
  4     /// 导入
  5     /// </summary>
  6     /// <param name="sender"></param>
  7     /// <param name="e"></param>
  8     protected void btnImport_Click(object sender, EventArgs e)
  9     {
 10         string fileName = UpLoadTxt.FileName;//获取要导入的文件名  
 11         if (fileName == null || fileName == "")
 12         {
 13             Response.Write("<script>alert(‘没有要导入的文件,请选中文件后再操作!‘);window.location.href=‘SNSbbsList.aspx‘;</script>");
 14         }
 15         else
 16         {
 17             string savePath = Server.MapPath("~/UploadFiles/ChatLog/");
 18             DateTime dtnow = System.DateTime.Now;
 19             string filename = dtnow.Year.ToString() + dtnow.Month.ToString() + dtnow.Day.ToString() + dtnow.Hour.ToString() + dtnow.Minute.ToString() + dtnow.Second.ToString() + dtnow.Millisecond.ToString();
 20             string ExtName = getFileExt(fileName).ToUpper();
 21             if (IsConform(ExtName) == false)
 22             {
 23                 Response.Write("<script>alert(‘上传的文件类型不是Excel文件,请核实后再上传!‘);window.location.href=‘SNSbbsList.aspx‘;</script>");
 24             }
 25             else
 26             {
 27                 filename += "." + ExtName;
 28                 FileOperatpr(filename, savePath);
 29                 string url = savePath + filename;
 30                 UpLoadTxt.SaveAs(url);
 31                 SqlConnection conn = SqlHelperEx.ConnOpen("SPSDB");
 32                 Method(conn, url);
 33                 SqlHelperEx.ConnClose(conn);
 34             }
 35         }
 36     }
 37 
 38 
 39     #region 辅助功能
 40 
 41     private string getFileExt(string fileName)//获取上传文件的后缀名
 42     {
 43         if (fileName.IndexOf(".") == -1)
 44             return "";
 45         string[] temp = fileName.Split(.);
 46         return temp[temp.Length - 1].ToLower();
 47     }
 48 
 49     private bool IsConform(string _extname)//判断文件类型是否符合
 50     {
 51         bool flag = false;
 52         if (_extname.ToLower() == "xls" || _extname.ToLower() == "xlsx")
 53         {
 54             flag = true;
 55         }
 56         return flag;
 57     }
 58 
 59     private void FileOperatpr(string fileName, string savePath)
 60     {
 61         if (!Directory.Exists(savePath))
 62         {
 63             Directory.CreateDirectory(savePath);
 64         }
 65         if (File.Exists(savePath + fileName))
 66         {
 67             File.Delete(savePath + fileName);
 68         }
 69     }
 70 
 71     #endregion
 72 
 73     protected void Method(SqlConnection conn, string url)
 74     {
 75         string istrue = "0";
 76         DataTable dt = new DataTable();
 77         dt = FromExcelToDataTable(url);
 78         if (dt.Rows.Count > 0)
 79         {
 80             try
 81             {
 82                 istrue = BulkCopy(conn, dt);
 83             }
 84             catch (Exception ex)
 85             {
 86                 istrue = "0";
 87             }
 88             if (istrue != "0")
 89             {
 90                 if (istrue != "" && istrue != "1")
 91                 {
 92                     Response.Write("<script>alert(‘网站为" + istrue + "出现了重复,请核实后再次操作!‘);window.location.href=‘SNSbbsList.aspx‘;</script>");
 93                 }
 94                 if (istrue == "1")
 95                 {
 96                     Response.Write("<script>alert(‘导入成功!‘);window.location.href=‘SNSbbsList.aspx‘;</script>");
 97                 }
 98             }
 99             else
100             {
101                 Response.Write("<script>alert(‘导入失败,请重新查看文件后再上传!‘);window.location.href=‘SNSbbsList.aspx‘;</script>");
102             }
103         }
104         else
105         {
106             Response.Write("<script>alert(‘导入的文件中没有数据或者格式不正确,请核实文件!‘);window.location.href=‘SNSbbsList.aspx‘;</script>");
107         }
108     }
109 
110 
111     protected DataTable FromExcelToDataTable(string physicalPath)
112     {
113         string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + physicalPath + ";Extended Properties=‘Excel 8.0;HDR=yes ;IMEX=1‘";
114         //  Excel 2007
115         if (physicalPath.ToLower().IndexOf(".xlsx") > 0 && physicalPath.ToLower().EndsWith("xlsx"))
116         {
117             strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=‘" + physicalPath + "‘;Extended Properties=‘Excel 8.0;HDR=yes;IMEX=1‘";
118         }
119         //  Excel 2003
120         if (physicalPath.ToLower().IndexOf(".xls") > 0 && physicalPath.ToLower().EndsWith("xls"))
121         {
122             strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=‘Excel 8.0;HDR=YES;‘;Data Source=‘" + physicalPath + "";
123         }
124         DataTable dt = new DataTable();
125 
126         OleDbConnection conn = new OleDbConnection(strConn);
127         try
128         {
129             if (conn.State.ToString() == "Closed")
130             {
131                 conn.Open();
132             }
133             DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
134             for (int i = 0; i < dtSheet.Rows.Count; i++)
135             {
136                 DataSet dst = new DataSet();
137                 dst.Clear();
138                 string strSheetName = dtSheet.Rows[i]["TABLE_NAME"].ToString();
139                 OleDbDataAdapter OleDa = new OleDbDataAdapter("select * from [" + strSheetName + "]", conn);
140                 OleDa.Fill(dst, "TableName");
141                 DataTable dtnew = dst.Tables[0];
142 
143                 dt.Columns.Add("classID", typeof(string));
144                 dt.Columns.Add("CategoryID", typeof(string));
145                 dt.Columns.Add("SNSName", typeof(string));
146                 dt.Columns.Add("accountID", typeof(string));
147                 dt.Columns.Add("URL", typeof(string));
148                 dt.Columns.Add("Area", typeof(string));
149                 dt.Columns.Add("fans", typeof(string));
150                 dt.Columns.Add("IsTiop", typeof(string));
151                 dt.Columns.Add("highlight", typeof(string));
152                 dt.Columns.Add("Stars", typeof(string));
153                 dt.Columns.Add("LinkWay", typeof(string));
154                 dt.Columns.Add("media", typeof(string));
155                 dt.Columns.Add("SNSContact", typeof(string));
156 
157 
158                 if (dtnew.Rows.Count > 0)
159                 {
160                     #region 匹配
161                     if (dtnew.Columns.Count >= 13)
162                     {
163                         for (int j = 0; j < dtnew.Rows.Count; j++)
164                         {
165                             DataRow row = dt.NewRow();
166                             try
167                             {
168                                 row["classID"] = dtnew.Rows[j]["类型"].ToString();
169                                 row["CategoryID"] =dtnew.Rows[j]["分类"].ToString();
170                                 row["SNSName"] = dtnew.Rows[j]["网站"].ToString();
171                                 row["accountID"] = dtnew.Rows[j]["板块"].ToString();
172                                 row["URL"] = dtnew.Rows[j]["链接"].ToString();
173                                 row["Area"] = dtnew.Rows[j]["地域"].ToString();
174                                 row["fans"] = ConvertDigit(dtnew.Rows[j]["粉丝(关注)数"].ToString());
175                                 row["IsTiop"] = dtnew.Rows[j]["置顶/天"].ToString();
176                                 row["highlight"] = dtnew.Rows[j]["加精/周"].ToString();
177                                 row["Stars"] = ConvertDigit(dtnew.Rows[j]["星级"].ToString());
178                                 row["LinkWay"] = dtnew.Rows[j]["直接联系方式"].ToString();
179                                 row["media"] = dtnew.Rows[j]["媒介"].ToString();
180                                 row["SNSContact"] = dtnew.Rows[j]["媒介联系方式"].ToString();
181 
182                             }
183                             catch (Exception)
184                             {
185                                 row = null;
186                             }
187                             if (row != null)
188                             {
189                                 dt.Rows.Add(row);
190                             }
191                         }
192                     }
193                     #endregion
194 
195                 }
196             }
197 
198 
199             conn.Close();
200         }
201         catch (Exception ex)
202         {
203             dt = null;
204         }
205         return dt;
206     }
207 
208 
209     #region 数据转换
210 
211 
212     protected float ConvertFloat(string numerator, string denominator)
213     {
214         float flag = 0F;
215         try
216         {
217             float _numer = ConvertFloat(numerator);
218             int _denom = ConvertDigit(denominator);//判断分母是否为0
219             if (_denom != 0)
220             {
221                 flag = _numer / _denom;
222             }
223         }
224         catch (Exception ex)
225         {
226             flag = 0F;
227         }
228         return flag;
229     }
230 
231 
232     protected float ConvertFloat(string str)
233     {
234         float flag = 0F;
235         try
236         {
237             flag = float.Parse(str);
238         }
239         catch (Exception ex)
240         {
241             flag = 0F;
242         }
243 
244         return flag;
245 
246     }
247 
248 
249 
250 
251 
252 
253     /// <summary>
254     /// 转化为金融类型(默认为0)
255     /// </summary>
256     /// <param name="str">代转化的字符串</param>
257     /// <returns></returns>
258     protected decimal ConvertDecimal(string str)
259     {
260         decimal flag = 0;
261         try
262         {
263             flag = Convert.ToDecimal(str);
264         }
265         catch (Exception ex)
266         {
267             flag = 0;
268         }
269         return flag;
270     }
271 
272     /// <summary>
273     /// 字符串类型转化成数字(转化失败时默认为0)
274     /// </summary>
275     /// <param name="str">代转化的字符串</param>
276     /// <returns>转化后的数字</returns>
277     protected int ConvertDigit(string str)
278     {
279         int flag = 0;
280         try
281         {
282             flag = Convert.ToInt32(str);
283         }
284         catch (Exception ex)
285         {
286             flag = 0;
287         }
288         return flag;
289     }
290 
291     #endregion
292 
293 
294     protected string BulkCopy(SqlConnection conn, DataTable dt)
295     {
296         string StrAgaionstraccount = "";
297         string CalssID = "";
298         string CategoryID = "";
299         if (dt != null && dt.Rows.Count > 0)
300         {
301             string sqlsnsname = "SELECT *,SNSName FROM  BaseSNSInfo WHERE IsValid=1 and classID=1  ORDER BY id DESC";
302             DataTable dtSNS = SqlHelper.GetDataTable(sqlsnsname, conn);
303             string sqllt = "SELECT * FROM BaseSNSClass WHERE IsValid=1 and id=1 or Name LIKE ‘%论坛%‘ ";
304             DataTable dtlt = SqlHelperEx.GetDataTable(sqllt, conn);
305             ///类型和分类
306             string sqlGetCates = "SELECT *,DictID,DictName FROM BaseCategoryName WHERE  IsValid=1  AND DictType=‘CategoryID‘";
307             DataTable dtGetCate = SqlHelperEx.GetDataTable(sqlGetCates, conn);
308             for (int k = 0; k < dt.Rows.Count; k++)
309             {
310                 CalssID = dt.Rows[k]["classID"].ToString();
311 
312                 if (dt.Rows.Count > 0)
313                 {
314                     for (int i = 0; i < dtlt.Rows.Count; i++)
315                     {
316                         if (dtlt.Rows[i]["Name"].ToString() == CalssID)
317                         {
318                             CalssID = dtlt.Rows[i]["ID"].ToString();
319                             break;
320                         }
321                     }
322                 }
323                 CategoryID = dt.Rows[k]["CategoryID"].ToString();
324                 if (dtGetCate.Rows.Count > 0)
325                 {
326                     for (int j = 0; j < dtGetCate.Rows.Count; j++)
327                     {
328                         if (dtGetCate.Rows[j]["DictName"].ToString() == CategoryID)
329                         {
330                             CategoryID = dtGetCate.Rows[j]["DictID"].ToString();
331                             break;
332                         }
333                     }
334                 }
335 
336                 string CreateLoginId = Session["UserName"].ToString();
337                 string straccount = dt.Rows[k]["SNSName"].ToString();
338                 int g = 0;
339                 if (dtSNS.Rows.Count > 0)
340                 {
341 
342                     for (; g < dtSNS.Rows.Count; g++)
343                     {
344                         if (dtSNS.Rows[g]["SNSName"].ToString() == straccount)
345                         {
346                             StrAgaionstraccount += straccount + ",";
347                             break;
348                         }
349                     }
350                 }
351                 if (g == dtSNS.Rows.Count)
352                 {
353                     StringBuilder strSql = new StringBuilder();
354                     // 生成SQL语句;
355                     strSql.AppendFormat("INSERT INTO BaseSNSInfo(classID,CategoryID,SNSName,accountID,URL,Area,fans,IsTiop,highlight,Stars,media,SNSContact,LinkWay,CreateUserId)  values(  {0}", Environment.NewLine);
356                     strSql.AppendFormat(" @classID,@CategoryID,@SNSName,@accountID,@URL,@Area,@fans,@IsTiop,@highlight,@Stars,@media,@SNSContact,@LinkWay,@CreateUserId) {0}", Environment.NewLine);
357                     SqlParameter[] parameters = {
358                                     new SqlParameter("@classID", CalssID),
359                                     new SqlParameter("@CategoryID", CategoryID ),
360                                     new SqlParameter("@SNSName",  straccount),
361                                     new SqlParameter("@accountID",  dt.Rows[k]["accountID"].ToString()),
362                                     new SqlParameter("@URL",  dt.Rows[k]["URL"].ToString()),
363                                     new SqlParameter("@Area",  dt.Rows[k]["Area"].ToString()),
364                                     new SqlParameter("@fans",  dt.Rows[k]["fans"].ToString()),
365                                     new SqlParameter("@IsTiop",  dt.Rows[k]["IsTiop"].ToString()),
366                                     new SqlParameter("@highlight",  dt.Rows[k]["highlight"].ToString()),
367                                     new SqlParameter("@Stars",  dt.Rows[k]["Stars"].ToString()),
368                                     new SqlParameter("@media",  dt.Rows[k]["media"].ToString()),
369                                     new SqlParameter("@SNSContact",  dt.Rows[k]["SNSContact"].ToString()),
370                                     new SqlParameter("@LinkWay",  dt.Rows[k]["LinkWay"].ToString()),
371                                     new SqlParameter("@CreateUserId", CreateLoginId),
372                                     };
373                     // 执行
374                     int results = SqlHelperEx.ExecuteNonQuery(strSql.ToString(), conn, parameters);
375                     // 返回
376                     if (results == 1)
377                     {
378                         StrAgaionstraccount = "1";
379                     }
380                     else
381                     {
382                         StrAgaionstraccount = "0";
383                     }
384                 }
385             }
386         }
387         return StrAgaionstraccount;
388     }
389     #endregion

 

C#Excel导出,导入操作

标签:

原文地址:http://www.cnblogs.com/hulxm/p/4935563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!