2011-02-07 64 views
1

我使用互操作,以.xls文件轉換爲HTML:.NET互操作Excel中爲HTML

if (!File.Exists(path)) 
    CreateExcel(datetime, path); 

string inputFileName = path + datetime.ToString("ddMMyyyyHHmmss")+ ".xls"; 
Microsoft.Office.Interop.Excel.Application excel = null; 
Microsoft.Office.Interop.Excel.Workbook xls = null; 
try 
{ 
    excel = new Microsoft.Office.Interop.Excel.Application(); 
    object missing = Type.Missing; 
    object trueObject = true; 
    excel.Visible = false; 
    excel.DisplayAlerts = false; 
    xls = excel.Workbooks.Open(inputFileName, missing, trueObject, missing, 
    missing, missing, missing, missing, missing, missing, missing, missing, 
    missing, missing, missing); 
    object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml; 
    System.Collections.IEnumerator wsEnumerator = 
    excel.ActiveWorkbook.Worksheets.GetEnumerator(); 
    int i = 1; 
    while (wsEnumerator.MoveNext()) 
    { 
     Microsoft.Office.Interop.Excel.Worksheet wsCurrent = 
     (Microsoft.Office.Interop.Excel.Worksheet)wsEnumerator.Current; 
     String outputFile = path + datetime.ToString("ddMMyyyyHHmmss")+".html"; 
     wsCurrent.SaveAs(outputFile, format, missing, missing, missing, 
     missing, missing, missing, missing, missing); 
     ++i; 
    } 
} 
catch (System.Runtime.InteropServices.COMException ex) 
{ 
} 
finally 
{ 
    excel.Application.Quit(); 
    excel.Quit(); 
    Marshal.ReleaseComObject(xls); 
    Marshal.ReleaseComObject(excel); 
    excel = null; 
} 

而在最後我得到的HTML文件,沒有「風格」。例如,文檔會丟失Excel文件所具有的所有顏色。我錯過了什麼?

+1

1);'到您的文件和你的代碼的頂部將是更清潔。 2)foreach循環會爲你做迭代,你不使用'i'計數器。 3)不要默默壓制例外。 – unholysampler

+0

[如何使用INLINE CSS將Excel電子表格導出爲HTML表格?](http://stackoverflow.com/questions/18436370/how-to-export-excel-spreadsheet-to-html-table-with-inline -css) –

+0

@PaulSweatte - 我不這麼認爲 –

回答

0

對我來說,工作完全加入`使用的Microsoft.Office.Interop.Excel

Dim excel As New Microsoft.Office.Interop.Excel.Application 
Dim xls As Microsoft.Office.Interop.Excel.Workbook 
xls = excel.Workbooks.Open("D:\Users\A\Desktop\$R39M2VD\Nouveau Feuille Microsoft Office Excel.xlsx") 
xls.SaveAs("D:\Users\A\Desktop\exported.html", XlFileFormat.xlHtml)