我是.net和epplus的新手。我的任务是读取Excel文件并将其上传到SQLserver。并非excel文件中的所有数据。只有少数列和行应映射到SQL表中。
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;
}
}
}
,aspx页面是
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Export" OnClick="btnUpload_Click" />
</div>.
有人可以建议这是正确的方法,还是一段代码将数据读取到sql server。