2015-06-03 47 views
10

我已出口使用的HttpContext用表,TR和TD格式从数据库中的数据。我想读取相同的文件并转换为数据表。如何导入Excel的是HTML格式

<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中的数据。

+0

嗨!你有没有看过[this](https://github.com/paulyoder/LinqToExcel/blob/master/readme.markdown)? –

+0

如果您将其导出为html格式(表格中包含trs和tds),为什么您将它视为excel? –

+0

@MladenOršolić:我得到了SAP创建的Excel,它以HTML格式导出到Excel。 – Wanderer

回答

0

我发现这个在线: C# Excel file OLEDB read HTML IMPORT

在这里,他们说:

除了使用SHEETNAME的,你必须使用 select语句的网页标题,而不$。 SELECT * FROM [HTMLPageTitle]

在那个岗位他们也链接到本手册,这可能会派上用场,但太长复制到这里: http://ewbi.blogs.com/develops/2006/12/reading_html_ta.html

如果不工作,我认为你将不得不重新创建原始Excel所以它仍然是一个Excel文件,而不是HTML(如果在你的情况是在所有可能的)

0

您可能会面临这个问题,由于不同的原因。对于这其中的一种解决方案,有不同的解决方案是使您的解决方案调试为x86。以下是如何将其更改为x86

  • 右键单击Visual Studio中的sloution。从Active solution platform
  • 单击配置管理器
  • 选择x86如果有
  • 如果没有可用的点击New,然后选择或键入x86并单击确定。
  • 重建解决方案并运行您的应用程序。

如果此解决方案不能解决您的问题,您可能需要安装32 bit版本的office system drivers。这是一个完整的article解释问题。

0

了深入的研究后,我找到了解决办法。

首先通过使用下面的代码特定的Excel文件转换为HTML页面。我们不得不下载HTML字符串并提取内容。标签包含和标签,但它可能具有样式属性。所以首先我们必须避免这些样式属性,然后我们可以从表格中获取所需的内容。

string url = Server.MapPath("~/FolderName/Excelname.html"); 
WebClient wc = new WebClient(); 
string fileContent = wc.DownloadString(url); 

这里我们必须格式化HTML标签以避免样式属性。

const string msgFormat = "table[{0}], tr[{1}], td[{2}], a: {3}, b: {4}"; 
const string table_pattern = "<table.*?>(.*?)</table>"; 
const string tr_pattern = "<tr.*?>(.*?)</tr>"; 
const string td_pattern = "<td.*?>(.*?)</td>"; 
const string a_pattern = "<a href=\"(.*?)\"></a>"; 
const string b_pattern = "<b>(.*?)</b>"; 

通过循环后,我们可以发现<tr><td>元素。然后我们可以使用这种方法在<td></td>标签内获得内容。

private static List<string> GetContents(string input, string pattern) 
{ 
    MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.Singleline); 
    List<string> contents = new List<string>(); 
    foreach (Match match in matches) 
    contents.Add(match.Value); 
    return contents; 
} 

然后我们可以将导入的记录按行插入数据库。

Reference link here

3

我认为这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(); 
相关问题