【问题标题】:upload excel and import to datatable上传excel并导入数据表
【发布时间】:2011-08-28 15:36:02
【问题描述】:

我正在尝试,用户从 uploadcontrol 中选择 excel 文件并上传或显示文件的完整路径/目录,因为我将解析文件并更新到数据表。

我在下面导入到 dataable 代码,我如何解决这种情况

用asp.net 4.0 ,c#开发项目

public DataTable Import(String path){

Microsoft.Office.Interop.Excel.ApplicationClass app = new Microsoft.Office.Interop.Excel.ApplicationClass();
    Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

    Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.ActiveSheet;

    int index = 0;
    object rowIndex = 2;

    DataTable dt = new DataTable();
    dt.Columns.Add("FirstName");
    dt.Columns.Add("LastName");
    dt.Columns.Add("Mobile");
    dt.Columns.Add("Landline");



    DataRow row;

    while (((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2 != null)
    {
        rowIndex = 2 + index;
        row = dt.NewRow();
        row[0] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2);
        row[1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 2]).Value2);
        row[2] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 3]).Value2);
        row[3] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 4]).Value2);

        index++;
        dt.Rows.Add(row);
    }
    app.Workbooks.Close();
    return dt;
}

【问题讨论】:

  • 不建议在您的服务器上启动 Excel 实例。

标签: c# excel upload datatable


【解决方案1】:

正如 Svick 所说,您并没有真正提出问题,但与此同时,您可能想要调查 reading from Excel using ADO.Net,这将使您只需几个步骤即可从 Excel 工作表创建数据集。或者,也许其中一个可以读/写 Excel 工作表的第三方组件适合您(我想到了 Flexcel 和 Gembox)。所有这些都具有您不需要在运行应用程序的计算机上安装 Excel 的优点。 (参见 Mathias 的评论)。

【讨论】:

    【解决方案2】:

    使用GemBox.Spreadsheet,您可以非常轻松地完成这项任务。

    这是一个示例Excel C# 代码:

    ExcelFile ef = new ExcelFile();
    
    ef.LoadXls(path);
    
    DataTable dt = ef.Worksheets[0].CreateDataTable(ColumnTypeResolution.Auto);
    
    return dt;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多