2012-08-09 117 views
1

我必須從頁面中的表中顯示的數據創建一個.xls文件。這發生在用戶點擊「導出」按鈕時。我有下面的代碼,它創建好了。現在,我想在同一個點擊中打開這個文件。我應該如何打開它才能讓用戶看到它?ASP.NET MVC打開一個.xls文件

string filePath = "C:/Upload/Stats_" + viewModel.SelectedTest.ToString() + ".xls"; 
      //write the header 
      using (var pw = new StreamWriter(filePath, true)) 
      { 
       pw.WriteLine(String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}", "Month", "Total Users", "K", 
              "T", "G", "Detail", "GS", 
              "BI", "GHF","A")); 

       //write to the file 

       for (int i = 0; i < 12; i++) 
       { 
        pw.WriteLine(
         String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}", viewModel.Months[i], 
             viewModel.M[i], viewModel.MKau[i], 
             viewModel.MTech[i], viewModel.MGew[i], 
             viewModel.MDet[i], viewModel.MGes[i], 
         viewModel.MBea[i], viewModel.MGesHf[i],viewModel.MAug[i])); 
        pw.Flush(); 
       } 

       pw.Close(); 
      } 

這裏我想打開它。

回答

0

我有相同的'要求'能夠導出到xls,而是我給客戶端導出到csv,如果您在安裝有excel的機器上,但也可用於其他系統。我是這樣實現的。

創建支持.AsCsv擴展方法,這是從Mike Hadlow's實施在很大程度上採取

public static class EnumerableExtensions 
{ 
    public static string AsCsv<T>(this IEnumerable<T> items) where T : class 
    { 
     var csvBuilder = new StringBuilder(); 
     var properties = typeof(T).GetProperties(); 
     foreach (T item in items) 
     { 
      string line = string.Join(",", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray()); 
      csvBuilder.AppendLine(line); 
     } 

     return csvBuilder.ToString(); 
    } 

    private static string ToCsvValue<T>(this T item) 
    { 
     if (item is string) 
     { 
      return string.Format("\"{0}\"", item.ToString().Replace("\"", "\\\"")); 
     } 

     double dummy; 
     if (double.TryParse(item.ToString(), out dummy)) 
     { 
      return string.Format("{0}", item.ToString()); 
     } 

     return string.Format("\"{0}\"", item.ToString()); 
    } 

} 

那麼你就需要設置你的控制器方法控制器方法中返回一個FileContentResult,並有一定的邏輯是這樣的:

var outputModel = viewModel.ToList().Select(model => new 
{ 
       Months = model.Months 
       M = model.M[i], 
       MKau= model.MKau, 
       MTech = model.MTech, 
       MGew = model.MGew, 
       MDet = model.MDet, 
       MGes = model.MGes, 
       MBea= model.MBea, 
       MGesHf= model.MGesHf 
}); 

string csv = "\"Month\",\"Total Users\",\"K\",\"T\",\"G\",\"Detail\",\"GS\",\"BI\",\"GHF\",\"A\"" 
         + System.Environment.NewLine 
         + outputModel.AsCsv(); 
string fileName = "Stats_" + viewModel.SelectedTest.ToString() + ".csv" 

return this.File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", fileName); 
相關問題