I am new to .net and epplus. I have task to read an excel file and upload it to SQLserver. Not all the data from the excel file. Only few columns and rows that should be mapped into SQL table.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string FilePath = string.Concat("~path" + FileUpload1.FileName);
FileUpload1.SaveAs(FilePath);
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
int i = 2;
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value.ToString().Trim());
}
}
}
}
catch (Exception ex)
{
Label1 = ex.Message;
}
}
}
and the aspx page is
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Export" OnClick="btnUpload_Click" />
</div>.
Can someone suggest whether this is the right approach and also piece of code to read the data to sql server.