none
How to read and write a csv or excel file in C#?

    Question

  • Hi
    I need to upload a csv or excel file which has one column (A) to an aspx page.
    It can read the row data one by one and insert into MSSQL DB.
    After the row of data inserted into MSSQL DB,  it needs to write the text "Inserted" in column B of the csv or excel file.

    If there is interruption such as DB connection error, those row of data had not been inserted will not marked in column B of the csv or excel file.

    How should I do that? 

     

    • Moved by Peter RitchieMVP, Moderator Wednesday, September 10, 2008 3:51 PM nothing to do with C# language syntax (Moved from Visual C# Language to Visual C# General)
    Wednesday, September 10, 2008 3:38 PM

Answers

  • CSV files should be fairly easy, after all it's just delimited text files that you can read/write with the System.IO classes.

    For Excel support, you probably need a third party library or something like Excel Services to edit the file.

    Mattias, C# MVP
    • Marked as answer by jack 321 Monday, September 15, 2008 3:39 AM
    Thursday, September 11, 2008 7:58 AM

All replies

  • CSV files should be fairly easy, after all it's just delimited text files that you can read/write with the System.IO classes.

    For Excel support, you probably need a third party library or something like Excel Services to edit the file.

    Mattias, C# MVP
    • Marked as answer by jack 321 Monday, September 15, 2008 3:39 AM
    Thursday, September 11, 2008 7:58 AM
  • Hi,

    You can try this C# Excel library to read / write CSV, XLS, XLSX files.

    Here is a sample C# code:

    ExcelFile ef = new ExcelFile();
     
    // Loads Excel file.
    ef.LoadXls("filename.xls");
     
    // Selects first worksheet.
    ExcelWorksheet ws = ef.Worksheets[0];
     
    // Change the value of the cell "A1".
    ws.Cells["A1"].Value = "Hello world!";
     
    // Saves the file in XLS format.
    ef.SaveXls("NewFile.xls");

    Tuesday, May 08, 2012 9:21 AM