天天看點

C#實作上傳/下載下傳Excel文檔

要求

環境資訊:WIN2008SERVER  開發工具:VS2015 開發語言:C#

要求:

  1.點選同步資料後接口擷取資料展示頁面同時過濾無效資料并寫入資料庫,資料可導出Excel并支援分類導出

  2.Excel導入确認資料,調用服務處理資料後寫入資料庫,并支援分類導出

這兩天搞了一個小功能,其他的不說了針對Excel導入導出做一個小總結

導出檔案

這裡的檔案導出是底層寫好的,個人了解有限而且畢竟屬于公司就不貼具體代碼了,簡單說一下思路

首先是建立導出Excel管理類,用于管理Excel檔案導出的模闆 樣式 每行的計算方式等等,當然需要在項目中添加該管理類的配置檔案去比對對應模闆;

1.讀取對應配置檔案,擷取配置檔案模闆資訊 至于模闆如何配置就不說啦xml檔案操作園子裡面很多篇關于這個文章

C#實作上傳/下載下傳Excel文檔

2.根據XML檔案定義模闆id周遊查詢到該模闆,這裡有緩存機制為了可能處于兩方面考慮,1,防止頻繁讀取周遊檔案進而減少性能缺失 2.弱誤删配置檔案程式不會立即停止工作,監控警報會首先暴露這個問題

C#實作上傳/下載下傳Excel文檔

3.最後就是讀取指定id下面的具體導出設定,比如标題頭,上限行數,給定簡單預設值等等細節處理,同時也含有緩存機制

C#實作上傳/下載下傳Excel文檔

配置檔案模闆管理大緻上有以上幾種功能,下面就是具體資料庫導出,還是那樣不能提供具體代碼但是思路可以說一說

導出管理類需要承接很多任務,入資料庫查詢,資料過濾,導出格式控制,導出日志設定,導出預警等等

C#實作上傳/下載下傳Excel文檔

其實這并不是一個簡單的excel導出工具而是一個小型的導出平台,承接一個導出實體去設定導出的各項資料,但是還是需要開發者根據自己的需求去填寫相應的模闆,導出格式,資料驗證,資料查詢方式實體承接了導出方式

(xls或者csv等等很多格式)使用者隻需要寫入具體導出DB資訊,以及導出表名稱和配置檔案以及資料驗證就可以輕松使用它完成資料導出操作

C#實作上傳/下載下傳Excel文檔

并且,針對檔案導出操作尤其是資料庫最好由底層實作通過response流發送到頁面執行下載下傳,資料相對規整一些如果在頁面直接執行導出頁面有些太沉重了 畢竟這個是可以實作的

導入檔案

 導入檔案首先需要上傳,檔案上傳至伺服器指定位址之後再去針對伺服器檔案解析,其實原理很簡單,就是通過解析上傳的檔案通過OLDB方式擷取解析後的檔案DataSet然後在寫入資料庫,下面是一個上傳檔案格式驗證

C#實作上傳/下載下傳Excel文檔

具體的讀取方法就很簡單了 網上一搜一大把,不過要區分一下版本而且不同版本的excel檔案行數上線不同下面貼一個我常用的excel到dataset方法

1 public static ReturnValue ReadExcelToDataSet(string xlsFullFileName, bool isHDR, bool isIMEX, int limitSheetCount, bool isOnlyVerify)
  2 {
  3     ReturnValue returnValue = new ReturnValue();
  4     string fileExt = UploadFileUtils.GetFileExt(xlsFullFileName);
  5     if (string.IsNullOrEmpty(fileExt) || !StringUtils.IsInLimitStr("xls,xlsx", fileExt))
  6     {
  7         returnValue.HasError = true;
  8         returnValue.ReturnCode = 1;
  9         returnValue.Message = "無效excel檔案字尾";
 10         return returnValue;
 11     }
 12     if (!File.Exists(xlsFullFileName))
 13     {
 14         returnValue.HasError = true;
 15         returnValue.ReturnCode = 2;
 16         returnValue.Message = "檔案不存在";
 17         return returnValue;
 18     }
 19     StringBuilder stringBuilder = new StringBuilder();
 20     string str;
 21     if ("xlsx".Equals(fileExt, StringComparison.CurrentCultureIgnoreCase))
 22     {
 23         stringBuilder.Append("Provider=Microsoft.ACE.OLEDB.12.0");
 24         str = "Excel 12.0;";
 25     }
 26     else
 27     {
 28         stringBuilder.Append("Provider=Microsoft.Jet.OLEDB.4.0");
 29         str = "Excel 8.0;";
 30     }
 31     stringBuilder.Append(";Data Source=" + xlsFullFileName);
 32     stringBuilder.Append(";Extended Properties=\"" + str);
 33     if (isHDR)
 34     {
 35         stringBuilder.Append(";HDR=Yes");
 36     }
 37     if (isIMEX)
 38     {
 39         stringBuilder.Append(";IMEX=1");
 40     }
 41     stringBuilder.Append("\"");
 42     ExcelUtils.log.Debug(stringBuilder.ToString());
 43     OleDbConnection oleDbConnection = new OleDbConnection(stringBuilder.ToString());
 44     try
 45     {
 46         oleDbConnection.Open();
 47         DataTable oleDbSchemaTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[]
 48         {
 49             null,
 50             null,
 51             null,
 52             "Table"
 53         });
 54         if (oleDbSchemaTable == null || oleDbSchemaTable.Rows.Count == 0)
 55         {
 56             returnValue.HasError = true;
 57             returnValue.ReturnCode = 3;
 58             returnValue.Message = "讀取不到sheet的資訊";
 59             ReturnValue result = returnValue;
 60             return result;
 61         }
 62         if (isOnlyVerify)
 63         {
 64             returnValue.HasError = false;
 65             returnValue.Message = "讀取sheet資訊正确";
 66             returnValue.PutValue("dtSheet", oleDbSchemaTable);
 67             ReturnValue result = returnValue;
 68             return result;
 69         }
 70         int num = oleDbSchemaTable.Rows.Count;
 71         if (limitSheetCount > 0 && limitSheetCount < oleDbSchemaTable.Rows.Count)
 72         {
 73             num = limitSheetCount;
 74         }
 75         string[] array = new string[num];
 76         for (int i = 0; i < num; i++)
 77         {
 78             array[i] = oleDbSchemaTable.Rows[i]["TABLE_NAME"].ToString();
 79         }
 80         DataSet dataSet = new DataSet();
 81         for (int j = 0; j < num; j++)
 82         {
 83             string text = "select * from [" + array[j] + "]";
 84             ExcelUtils.log.Debug(text);
 85             OleDbCommand selectCommand = new OleDbCommand(text, oleDbConnection);
 86             OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(selectCommand);
 87             DataTable dataTable = new DataTable(array[j]);
 88             oleDbDataAdapter.Fill(dataTable);
 89             dataSet.Tables.Add(dataTable);
 90         }
 91         returnValue.HasError = false;
 92         returnValue.PutValue("dtSheet", oleDbSchemaTable);
 93         returnValue.PutValue("arrTableName", array);
 94         returnValue.ReturnObject = dataSet;
 95         returnValue.Message = "讀取成功";
 96     }
 97     catch (Exception ex)
 98     {
 99         returnValue.HasError = true;
100         returnValue.ReturnCode = -100;
101         returnValue.ReturnException = ex;
102         returnValue.Message = ex.Message;
103         ExcelUtils.log.WarnFormat("ReadExcelToDataSet sbConn={0} 出錯,原因:{1}", stringBuilder.ToString(), ex.Message);
104     }
105     finally
106     {
107         oleDbConnection.Close();
108     }
109     return returnValue;
110 }      

哦對 注意一下,如果用導出方法導出xls檔案再用導入方法導入該檔案會報錯的喲,我是預設儲存.csv 實際就為了确定檔案是否被使用過,是以當你的excel檔案能導出單相同檔案卻導入不了 請嘗試一下重新儲存一下.xls格式 在進行導入

C#實作上傳/下載下傳Excel文檔