使用c#在单个xlsx中读取多个Excel工作表

时间:2017-04-05 01:15:28

标签: c# excel epplus

我正在尝试开发一段代码,它将从单个xlsx中的3个工作表中获取数据,并将其上传到SQL Server上的3个不同的表。每个工作表都应该将其内容上传到一个表(工作表1上传到表Customer,工作表2上传到表Sales,...)

我设法让它将工作表1中的所有数据上传到表格......以下是代码:

public partial class LoggedHome : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    if (IsPostBack && Upload.HasFile)
    {
        if (Path.GetExtension(Upload.FileName).Equals(".xlsx")) 
        {
            var excel = new ExcelPackage(Upload.FileContent); 
            var dt = excel.ToDataTable(); 
            var table = "MenuPrice";
            using (var conn = new SqlConnection("Removed for security purpouses"))
            {
                var bulkCopy = new SqlBulkCopy(conn);
                bulkCopy.DestinationTableName = table;
                conn.Open();
                var schema = conn.GetSchema("Columns", new[] { null, null, table, null });
                foreach (DataColumn sourceColumn in dt.Columns)
                {
                    foreach (DataRow row in schema.Rows)
                    {
                        if (string.Equals(sourceColumn.ColumnName, (string)row["COLUMN_NAME"], StringComparison.OrdinalIgnoreCase))
                        {
                            bulkCopy.ColumnMappings.Add(sourceColumn.ColumnName, (string)row["COLUMN_NAME"]);
                            break;
                        }
                    }
                }
                bulkCopy.WriteToServer(dt);
            }
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('This is not an Excel file. Please upload a proper file.')", true);
        }
    }
}
}

public static class ExcelPackageExtensions
{
public static DataTable ToDataTable(this ExcelPackage package)
{
    ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
    DataTable table = new DataTable();
    foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
    {
        table.Columns.Add(firstRowCell.Text);
    }
    for (var rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
    {
        var row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];
        var newRow = table.NewRow();
        foreach (var cell in row)
        {
            newRow[cell.Start.Column - 1] = cell.Text;
        }
        table.Rows.Add(newRow);
    }
    return table;
}
}

非常感谢任何帮助!谢谢

1 个答案:

答案 0 :(得分:1)

此行仅检索第一个工作表

ExcelWorksheet workSheet = package.Workbook.Worksheets.First();

将其更改为for循环,就像您对单元格和行

所做的那样
DataTable table = new DataTable();
foreach (var workSheet in package.Workbook.Worksheets)
{
    // Existing code
}
return table;