Liu ChiaChi

Liu ChiaChi

  • NA
  • 18
  • 2.7k

Read a csv file using 2D array

Nov 20 2020 3:33 AM
I want to read a csv file using 2D array, there will be an exception error, please help me
  1. private void button1_Click(object sender, EventArgs e)  
  2. {  
  3.     //new a excel  
  4.     Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();  
  5.     excel.Application.Workbooks.Add(true);  
  6.     if (openFileDialog1.ShowDialog() ==System.Windows.Forms.DialogResult.OK)  
  7.     {  
  8.         string theFile = openFileDialog1.FileName;   
  9.         Encoding enc = Encoding.GetEncoding("UTF-8");   
  10.         //var readText1 = File.ReadAllLines(theFile);  
  11.         var readText1 = System.IO.File.ReadAllLines(theFile);  
  12.         var readText = File.ReadAllLines(theFile).Select(l =>   
  13.              l.Split(',').ToArray()).ToArray();  
  14.         var rows = readText1.Count();  
  15.         //Number of rows columns  
  16.         var columns = readText1[0].Split(',').Count();  
  17.         //var columns = readText.Count();  
  18.         excel.Visible = true;  
  19.         for (int i = 0; i < rows; i++)  
  20.         {  
  21.             for (int j = 0; j < columns; j++)  
  22.             {  
  23.                 excel.Cells[i + 1, j + 1] = readText[j][i];  
  24.                 //Console.WriteLine();  
  25.             }  
  26.         }  
  27.     }  
  28. } 

Attachment: Source_code.zip

Answers (2)