Wednesday, May 13, 2020

Export array of data to excel in C#

Most of the time, we need to deal with data that also need to export to excel. So, the following method can export your string array to excel. lets have a look :

     public static bool ExportArrayToExcel(List<string[]> data, string filename, string[] headers=null, bool flOpenFile = false)  
     {  
       bool flExported = false;  
       try  
       {  
         SaveFileDialog sfd = new SaveFileDialog();  
         sfd.Filter = "Excel Documents (*.xls)|*.xls";  
         sfd.FileName = filename;  
         if (sfd.ShowDialog() == DialogResult.OK)  
         {  
           string stOutput = "";  
           string sHeaders = "";  
           if (headers.Count() > 0)  
           {  
             for (int j = 0; j < headers.Count(); j++)  
               sHeaders = sHeaders.ToString() + Convert.ToString(headers[j]) + "\t";  
             stOutput += sHeaders + "\r\n";  
           }  
           for (int i = 0; i < data.Count; i++)  
           {  
             string stLine = "";  
             for (int j = 0; j < data[i].Count(); j++)  
               stLine = stLine.ToString() + Convert.ToString(data[i][j]) + "\t";  
             stOutput += stLine + "\r\n";  
           }  
           Encoding utf16 = Encoding.GetEncoding(1254);  
           byte[] output = utf16.GetBytes(stOutput);  
           FileStream fs = new FileStream(sfd.FileName, FileMode.Create);  
           BinaryWriter bw = new BinaryWriter(fs);  
           bw.Write(output, 0, output.Length);   
           bw.Flush();  
           bw.Close();  
           fs.Close();  
           if (flOpenFile)  
           {  
             Process.Start(sfd.FileName);  
           }  
         }  
       }  
       catch (Exception)  
       {  
         throw;  
       }  
       return flExported;  
     }  

copy and paste and try.

happy coding..

No comments:

Post a Comment