以下使用office 2007为例,其他版本略有不同。
1添加引用,对于不同的版本,有所不一样。当然前提自然是安装了对应的微软office软件。
2转换代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Excel = Microsoft.Office.Interop.Excel; namespace CommonConvert { public class ExcelToHtml { /// <summary> /// 使用反射调用方法,返回生成的HTML文件路径 /// </summary> /// <param name="excelFileName"></param> /// <returns></returns> public string ExcelToHtmlFile(object excelFileName) { //在此处放置用户代码以初始化页面 Excel.Application excel = new Excel.Application(); Type wordType = excel.GetType(); Excel.Workbooks docs = excel.Workbooks; //打开文件 Type docsType = docs.GetType(); Excel.Workbook doc = (Excel.Workbook)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { excelFileName, true, true }); Type docType = doc.GetType(); string htmlFullFileName = excelFileName + ".html"; //HTML文件路径 object ofmt = Excel.XlFileFormat.xlHtml; //转换格式,另存为 docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { htmlFullFileName, ofmt}); docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null); //退出 wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, excel, null); return htmlFullFileName.ToString(); } /// <summary> /// 直接调用方法,不使用反射 /// </summary> /// <param name="excelFullFileName"></param> /// <returns></returns> public string ExcelToHtmlFile2(string excelFullFileName) { Excel.Application excel = new Excel.Application(); Excel.Workbooks docs = excel.Workbooks; //打开文件 // Excel.Workbook doc = docs.Open(excelFullFileName.ToString(), Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Excel.Workbook doc = docs.Open(excelFullFileName.ToString()); string htmlFullFileName = excelFullFileName + ".html"; //HTML文件路径 object ofmt = Excel.XlFileFormat.xlHtml; //转换格式,另存为 // doc.SaveAs(htmlFullFileName, ofmt, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // doc.SaveAs(htmlFullFileName, ofmt, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange); doc.SaveAs(htmlFullFileName, ofmt); doc.Close(); //退出 excel.Quit(); return htmlFullFileName; } } }