While searching for a functionality of importing excel to database using C#. I searched a lot and couldn't get an appropriate article for a very simple functionality. After 15 minutes of searching, I got some code with bugs in it. Rectified the same and it's for you.
Below is the code for importing excel data cell by cell. Enjoy coding
Excel.Application xlApp;
private void LeakageChecks_Load(object sender, EventArgs e){
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
string str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(@"C:\LeakData\LeakedData.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = Convert.ToString((range.Cells[rCnt, cCnt] as Excel.Range).Value2);
MessageBox.Show(str);
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech
No comments:
Post a Comment