Import and export package

Suhrob 1 Reputation point
2022-11-24T10:13:05.027+00:00

Dear developers.
Please tell me what is the preferred package in .NET for writing and reading excel, csv files ?

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 25,296 Reputation points
    2022-11-25T03:14:12.963+00:00

    @Suhrob , you could install nuget-package Microsoft.Office.Interop.Excel to read and write excel or csv files.

    Here is a code example I write about how to convert excel or csv file to datatable.

    public DataTable READExcel(string path)  
            {  
                Microsoft.Office.Interop.Excel.Application objXL = null;  
                Microsoft.Office.Interop.Excel.Workbook objWB = null;  
                objXL = new Microsoft.Office.Interop.Excel.Application();  
                objWB = objXL.Workbooks.Open(path);  
                Microsoft.Office.Interop.Excel.Worksheet objSHT = objWB.Worksheets[1];  
      
                int rows = objSHT.UsedRange.Rows.Count;  
                int cols = objSHT.UsedRange.Columns.Count;  
                DataTable dt = new DataTable();  
                int noofrow = 1;  
      
                for (int c = 1; c <= cols; c++)  
                {  
                    string colname = objSHT.Cells[1, c].Text;  
                    dt.Columns.Add(colname);  
                    noofrow = 2;  
                }  
      
                for (int r = noofrow; r <= rows; r++)  
                {  
                    DataRow dr = dt.NewRow();  
                    for (int c = 1; c <= cols; c++)  
                    {  
                        dr[c - 1] = objSHT.Cells[r, c].Text;  
                    }  
      
                    dt.Rows.Add(dr);  
                }  
      
                objWB.Close();  
                objXL.Quit();  
                return dt;  
            }  
    

    Please note that you need to install Office in your computer first of all.

    Hope my solution could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.