daily pastebin goal
56%
SHARE
TWEET

Untitled

a guest Mar 18th, 2019 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public void ExportToExcel()
  2.     {
  3.  
  4.         DataTable tblFiltered = _currentTable.AsEnumerable()
  5.                           .Where(r => r.Field<string>("Type") == ExportGridGroup)
  6.                           .CopyToDataTable();
  7.  
  8.         StringBuilder sb = new StringBuilder();
  9.         IEnumerable<string> columnNames = tblFiltered.Columns.Cast<DataColumn>().
  10.                                           Select(column => column.ColumnName);
  11.         sb.AppendLine(string.Join(",", columnNames));
  12.  
  13.         foreach (DataRow row in tblFiltered.Rows)
  14.         {
  15.             IEnumerable<string> fields = row.ItemArray.Select(field => """ + field.ToString() + """);
  16.             sb.AppendLine(string.Join(",", fields));
  17.         }
  18.  
  19.         String result = sb.ToString();
  20.         try
  21.         {
  22.             StreamWriter sw = new StreamWriter("export.csv");
  23.             sw.WriteLine(result);
  24.             sw.Close();
  25.             Process.Start("export.csv");
  26.         }
  27.         catch (Exception ex)
  28.         {
  29.             MessageBox.Show(ex.Message);
  30.         }
  31.     }
  32.      
  33. [TestMethod()]
  34.     public void ExportToExcelTest()
  35.     {
  36.         //Step 1: Creating a mock table with columns
  37.         DataTable testtable = new DataTable();
  38.         DataRow mydatarow;
  39.         mydatarow = testtable.NewRow();
  40.         //Step 2: Adding the row
  41.         mydatarow["ColumnA"] = "12345";
  42.         mydatarow["ColumnB"] = "test";
  43.  
  44.         testtable.Rows.Add(mydatarow);
  45.  
  46.         StringBuilder sb = new StringBuilder();
  47.         IEnumerable<string> columnNames = testtable.Columns.Cast<DataColumn>().
  48.                                           Select(column => column.ColumnName);
  49.         sb.AppendLine(string.Join(",", columnNames));
  50.  
  51.         foreach (DataRow row in testtable.Rows)
  52.         {
  53.             IEnumerable<string> fields = row.ItemArray.Select(field => """ + field.ToString() + """);
  54.             sb.AppendLine(string.Join(",", fields));
  55.         }
  56.  
  57.         String result = sb.ToString();
  58.         StreamWriter sw = new StreamWriter("export.csv");
  59.         sw.WriteLine(result);
  60.         sw.Close();
  61.         Process.Start("export.csv");          
  62.         Assert.Fail();
  63.     }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top