Tag: C#

How to read an Excel File with C#

Setelah nyari2 kemana2 dapet juga library buat baca tulis file excel di c#.

Setelah utak atik bentar jadilah kelas ExcelReader. Kelas ini membaca file Excel dengan memanfaatkan library excellibrary. http://code.google.com/p/excellibrary/

and. here is the code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Data;
using ExcelLibrary.Office.Excel;

namespace zaitun.Data
{
 public class ExcelReader
 {

private DataSet data;
private string filePath;

public ExcelReader(string filePath)
{
this.filePath = filePath;
}

public DataSet ReadData()
{
Workbook book = Workbook.Open(this.filePath);

this.data = new DataSet();

foreach (Worksheet sheet in book.Worksheets)
{
DataTable table = new DataTable(sheet.Name);
for (int i = sheet.Cells.FirstColIndex; i <= sheet.Cells.LastColIndex; i++)
{
table.Columns.Add();
}

for (int i = sheet.Cells.FirstRowIndex; i <= sheet.Cells.LastRowIndex; i++)
{
Row xlrow = sheet.Cells.GetRow(i);
DataRow row = table.NewRow();
for (int j = xlrow.FirstColIndex; j <= xlrow.LastColIndex; j++)
{
Cell cell = xlrow.GetCell(j);

row[j - xlrow.FirstColIndex] = cell.Value;
}

table.Rows.Add(row);
}

this.data.Tables.Add(table);
}

return this.data;
}
}

}

Kelas ini membaca file excel yang path-nya didefinisikan di konstruktor kelas ini yaitu parameter filePath.

Hasil pembacaannya diumpan balik dalam objek DataSet melalui fungsi Read Data. Objek dataset merepresentasikan satu workbook excel. didalam DataSet ada beberapa DataTable yang di excel berupa Worksheet.

Berikut contoh implementasi dari kelas excelreader

ExcelReader excel = new ExcelReader(filePath);
DataSet excelData = excel.ReadData();
Advertisements