Read Write Excel files in C# – sample source codes – Read from Excel File

  • Home
  • /
  • Articles
  • /
  • Read Write Excel files in C# – sample source codes – Read from Excel File

Read Write Excel files in C# tutorial shows how to write to and read from Excel file from your application using Speadsheet SDK. Use sample C# source codes below for Excel writing and reading. Read Excel file in C# with the help of the code below.
Write to Excel file from your application:

using System;
using System.Collections.Generic;
using System.Text;
using Bytescout.Spreadsheet;
using System.Diagnostics;
using System.IO;

namespace HelloWorld
{
   class Program
   {
       static void Main(string[] args)
       {
           // Create new Spreadsheet
           Spreadsheet document = new Spreadsheet();

           // add new worksheet
           Worksheet Sheet = document.Workbook.Worksheets.Add("FormulaDemo");           

           // headers to indicate purpose of the column
           Sheet.Cell("A1").Value = "Formula (as text)";
           // set A column width
           Sheet.Columns[0].Width = 250;

           Sheet.Cell("B1").Value = "Formula (calculated)";
           // set B column width
           Sheet.Columns[1].Width = 250;


           // write formula as text 
           Sheet.Cell("A2").Value = "7*3+2";
           // write formula as formula
           Sheet.Cell("B2").Value = "=7*3+2";

           // delete output file if exists already
           if (File.Exists("Output.xls")){
               File.Delete("Output.xls");
           }

           // Save document
           document.SaveAs("Output.xls");

           // Close Spreadsheet
           document.Close();

           // open generated XLS document in default program
           Process.Start("Output.xls");

       }

   }
}

Read from Excel from your application:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Bytescout.Spreadsheet;
using System.IO;

namespace HelloWorld
{
   class Program
   {
       static void Main(string[] args)
       {
           // Create new Spreadsheet
           Spreadsheet document = new Spreadsheet();
document.LoadFromFile("Sample.xls");

           // Get worksheet by name
           Worksheet worksheet = document.Workbook.Worksheets.ByName("Sheet1");

           // Check dates
           for (int i = 0; i < 4; i++)
           {
               // Set current cell
               Cell currentCell = worksheet.Cell(i, 0);

               DateTime date = currentCell.ValueAsDateTime;

               // Write Date
               Console.WriteLine("{0}", date.ToShortDateString());
           }

           // Close document
           document.Close();

           // Write message
           Console.Write("Press any key to continue...");

           // Wait user input
           Console.ReadKey();

       }
   }
}
prev
next