c# - 如何导入HTML格式的Excel

标签 c# asp.net excel import

我使用 HttpContext 从数据库中导出数据,格式为表、tr 和 td。我想读取同一个文件并转换成数据表。

<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='HTML Import;HDR={1};IMEX=1'" />

<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1};IMEX=1'" />

    private DataTable GetTableFromExcel()
    {
        DataTable dt = new DataTable();

        try
        {
            if (exclFileUpload.HasFile)
            {
                string FileName = Path.GetFileName(exclFileUpload.PostedFile.FileName);
                string Extension = Path.GetExtension(exclFileUpload.PostedFile.FileName);
                string FolderPath = Server.MapPath(ConfigurationManager.AppSettings["FolderPath"]);
                //string NewFileName = string.Format("{0}_{1}", DateTime.Now.ToString().Replace("/", "").Replace(" ", "").Replace(":", ""), FileName);
                string FilePath = Path.Combine(string.Format("{0}/{1}", FolderPath, FileName));
                exclFileUpload.SaveAs(FilePath);
                string conStr = "";
                switch (Extension)
                {
                    case ".xls": //Excel 97-03
                        conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                        break;
                    case ".xlsx": //Excel 07
                        conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                        break;
                }
                conStr = String.Format(conStr, FilePath, true);
                OleDbConnection connExcel = new OleDbConnection(conStr);
                OleDbCommand cmdExcel = new OleDbCommand();
                OleDbDataAdapter oda = new OleDbDataAdapter();

                cmdExcel.Connection = connExcel;

                connExcel.Open();
                DataTable dtExcelSchema;
                dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                connExcel.Close();

                connExcel.Open();
                cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
                oda.SelectCommand = cmdExcel;
                oda.Fill(dt);
                connExcel.Close();
                File.Delete(FilePath);

            }
        }
        catch (Exception ex)
        {

        }
        return dt;
    }

当使用第二个连接字符串时,出现错误“外部表不是 connection.Open() 上的预期格式。”但是当使用第一个时,我在读取工作表名称时出错。

请告诉我如何读取工作表或直接从 Excel 中读取数据。

最佳答案

我认为这Third party dll-(ExcellDataReader)可能有助于解决您的问题。

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())
{
    //excelReader.GetInt32(0);
}

//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

关于c# - 如何导入HTML格式的Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30613673/

相关文章:

c# - 导出到 Excel 错误

c# - 字段启动器(静态或非静态)和构造函数(静态或非静态)首先运行

c# - 论坛标签。实现它们的最佳方法是什么?

asp.net - 如何在标记中设置 DropDownList 选定项?

asp.net - Windows Azure 部署问题

excel - 在一个非常大的表中循环一个 if 函数。太慢了

c# - 在后台线程上初始化单例的常见模式

c# - 当属性值在 setter 内更改时更新 View

c# - 当函数属于必须解析的类时,如何向 Autofac 注册委托(delegate)或函数?

excel - 为什么 Excel 调用的 UDF 次数超出了要求?