2014-10-06 74 views
2

我有以下代碼,數據表已經有數據,我想將它導出到excel。 但是我收到以下警告,我試過xlsx,但它不起作用。 我也嘗試過csv,並且根據需要將數據打開成列。如何在導出數據表時刪除導出到excel警告

public static void ExportDatatabletoExcel(DataTable dt, List<string> columnNames) 
     { 
      try 
      { 
       const string attachment = "attachment; filename=elreport.xls"; 
       HttpContext.Current.Response.ClearContent(); 
       HttpContext.Current.Response.AddHeader("content-disposition", attachment); 
       HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; 
       string tab = ""; 
       foreach (DataColumn dc in dt.Columns) 
       { 
        if (!columnNames.Contains(dc.ColumnName)) continue; 
        HttpContext.Current.Response.Write(tab + dc.ColumnName); 
        tab = "\t"; 
       } 
       HttpContext.Current.Response.Write("\n"); 
       int i; 
       foreach (DataRow dr in dt.Rows) 
       { 
        tab = ""; 
        for (i = 0; i < dt.Columns.Count; i++) 
        { 
         if(!columnNames.Contains(dt.Columns[i].ColumnName)) continue; 
         HttpContext.Current.Response.Write(tab + dr[i].ToString()); 
         tab = "\t"; 
        } 


        HttpContext.Current.Response.Write("\n"); 
       } 
       HttpContext.Current.Response.End(); 
      } 
      catch (Exception ex) 
      { 
       string errorMessage = String.Format("ExportToExcelError: {0}", ex.Message); 
       LoggingService.LogError(LoggingCategory.General, ex, errorMessage); 
       throw; 
      } 
     } 

錯誤是:

+0

什麼版本的Excel? – Sorceri 2014-10-23 15:27:31

回答

3

有兩種確定方式,刪除警告。

  1. 使用的OpenXML API或EPPlus API建立一個有效的.xlsx文件(EPPlus更容易,實際上支持OLEDB進口)

  2. 構建文件爲.csv格式與.csv擴展名,但離開內容類型爲Excel,以便使用Excel打開。然而,你正在構建其需要的文件,你可能有正確與Excel閱讀的內容問題,方式加以解決:如果在某些方面格式化

Excel只能讀取CSV。此外,編碼必須是Windows 1252,假設您使用的是Excel窗口,否則將無法處理外部字符。還需要針對Excel專門處理來自郵政編碼等的前導零。

public static class CSVExportUtility 
    { 
    /// <summary> 
     /// Open a datatable in Excel 
     /// </summary> 
     /// <param name="dt"></param> 
     /// <param name="fileName"></param> 
     public static void OpenAsCSV(DataTable dt, string fileName) 
     { 
      CSVExportUtility.OpenAsCSV(DataTableToCSV(dt), fileName); // now open the file 
     } // OpenAsCSV 
    /// <summary> 
     /// open the content in the browser as a CSV 
     /// </summary> 
     /// <param name="sbCSVFileData"></param> 
     /// <param name="filename"></param> 
     public static void OpenAsCSV(StringBuilder sbCSVFileData, string fileName) 
     { 
      if (HttpContext.Current == null || HttpContext.Current.Response == null) 
       return; 

      HttpContext.Current.Response.Clear(); 
      HttpContext.Current.Response.AddHeader(
       "content-disposition", string.Format("attachment; filename={0}", fileName)); 
      HttpContext.Current.Response.ContentType = "application/ms-excel"; 

      // This is a little tricky. Would like to use utf-8 or unicode... but Excel on Windows uses 1252 by default so we need to keep the same so most users can read the file. 
      // At some point, we may need to actually convert our text from whatever .NET uses to 1252, but at the moment they seem similar enough that it is okay 
      HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding(1252); 

      // render the htmlwriter into the response 
      HttpContext.Current.Response.Write(sbCSVFileData.ToString()); 
      HttpContext.Current.Response.End(); 
     } 

static StringBuilder DataTableToCSV(DataTable dt) 
     { 
      StringBuilder sb = new StringBuilder(); 
      foreach (DataColumn dc in dt.Columns) 
      { 
       if (dc == dt.Columns[dt.Columns.Count - 1]) 
        CSVExportUtility.AddFieldForCSV(dc.ColumnName, sb, false, true); 
       else 
        CSVExportUtility.AddFieldForCSV(dc.ColumnName, sb, true, false); 
      } 
      foreach (DataRow dr in dt.Rows) 
      { 
       foreach (DataColumn dc in dt.Columns) 
       { 
        if (dc == dt.Columns[dt.Columns.Count - 1]) 
         CSVExportUtility.AddFieldForCSV(FormatDataValue(dr[dc.ColumnName]), sb, false, true); 
        else 
         CSVExportUtility.AddFieldForCSV(FormatDataValue(dr[dc.ColumnName]), sb, true, false); 
       } 
      } 
      return sb; 
     } 

    static string FormatDataValue(object dv) 
     { 
      if (dv == null) 
       return null; 
      if (dv is DateTime) 
       return ((DateTime)dv).ToShortDateString(); 
      else 
       return dv.ToString(); 
     } 

     /// <summary> 
     /// export text to a csv 
     /// </summary> 
     /// <param name="text"></param> 
     /// <param name="sbCSV"></param> 
     /// <param name="appendTrailingComma"></param> 
     /// <param name="endOfRow"></param> 
     public static void AddFieldForCSV(string text, StringBuilder sbCSV, bool appendTrailingComma, bool endOfRow) 
     { 
      // shouldn't start or end with whitespace, escape quotes 
      if (text != null) 
       text = text.Trim().Replace("\"", "\"\""); 

      // quote field 
      int testInt; 
      if (text != null && text.Trim().Length > 1 && text.Trim()[0] == '0' && int.TryParse(text.Trim(), out testInt)) 
      { // if text is numeric and starts with '0' tell excel to treat as string and not strip the zero. This ONLY works if it's numeric! Otherwise it fails, example ="a,b" will use 2 cells 
       text = "=\"" + text.Trim() + "\""; 
      } 
      else 
      { 
       text = "\"" + text + "\""; 
      } 

      sbCSV.Append(text); 
      if (appendTrailingComma) 
       sbCSV.Append(","); 
      if (endOfRow) 
       sbCSV.AppendLine(); 
     } 
} 

如果你正在尋找出口一個GridView而不是DataTable,這種解釋是: http://atakala.com/Browser/Item.aspx?user_id=amos&dict_id=2325 ;大部分代碼是相似的(CSVExportUtility方法)

+0

1252字符集也會解決這個問題:http://stackoverflow.com/questions/26524301/export-to-excel-names-with-accent-are-not-exported-correctlty? – 2014-10-24 06:55:55

3

This answerHow to suppress the file corrupt warning at Excel download?地址的一些問題。我建議檢查一下其他的答案。

警報是在Excel 2007中的新安全功能被叫分機 硬化,這就保證了文件內容被打開比賽 在試圖 打開文件的shell命令指定的擴展型。

...

此問題仍在調查中,但直到 辦公室14給出的代碼的複雜性質的修復是不太可能,而事實上 是Excel不希望降低安全措施解決方法 IE瀏覽器打開的行爲沒有完全瞭解其他瀏覽器用戶的後果 。

此外,this comment可能會有所幫助。

我認爲這隻適用於使用CSV並保存爲XLS的情況。 但是,如果你構建一個真正的Excel文件,那麼它應該沒問題。 CF9 cfspreadsheet將成爲你的朋友。 :) - 亨利6月25日09時23:53

其他來源進行檢查: