Friday, April 4, 2008

Reading/Writing Excel in C# using Interop

Add references to :
Microsoft Excel 10.0/11 Object Library using "add reference->com" tab. The following code shows example of reading and writing the xls:


using System;
using System.Collections.Generic;
using System.Text;
using Excel;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string path = @"C:\Documents and Settings\shivps\Desktop\cbit_codef\CBIT_CODEF\New Microsoft Excel Worksheet.xls";
Excel.ApplicationClass app = new ApplicationClass();
app.ShowWindowsInTaskbar = false;

Excel.Workbook wb = app.Workbooks.Open(
path,
0,
false,
5,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"\t",
true,
false,
0,
true,
1,
0);

Excel.Worksheet wsAuthor = null;
foreach (Excel.Worksheet ws in wb.Worksheets)
{
if (string.Compare("author", ws.Name, true) == 0)
{
wsAuthor = ws;
break;
}
}

// read all records
int row = 2; // leave first row
while (true)
{
if (((Excel.Range)wsAuthor.Cells[row, 1]).Value2 == null ||
((Excel.Range)wsAuthor.Cells[row, 2]).Value2 == null ||
((Excel.Range)wsAuthor.Cells[row, 3]).Value2 == null ||
((Excel.Range)wsAuthor.Cells[row, 4]).Value2 == null)
{
break;
}
string first = ((Excel.Range)wsAuthor.Cells[row, 1]).Value2.ToString();
string second = ((Excel.Range)wsAuthor.Cells[row, 2]).Value2.ToString();
string login = ((Excel.Range)wsAuthor.Cells[row, 3]).Value2.ToString();
string pass = ((Excel.Range)wsAuthor.Cells[row, 4]).Value2.ToString();

// create user
string status = "pass";
string error = "no error";

// update xls
wsAuthor.Cells[row, 5] = status;
wsAuthor.Cells[row, 6] = error;
row++;
}

wb.Save();
wb.Close(false, null, null);
app.Quit();
}

}
}

No comments: