.net 将excel转成html文件
最近在做一个打印预览功能,但是开始没有头绪后来用excel做了一个模板,然后根据excel模板来生成新的excel并将其存储为html,可以通过http请求在浏览器中读取,并且打印,其他的不多说。方法如下:
首先需要安装Office,然后引用Microsoft.Office.Interop.Excel.dll.
public void ExcelToHtmlFiled(string excelFileName, string rHtmlFilePath) { //实例化Excel Microsoft.Office.Interop.Excel.Application repExcel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workbook = null; Microsoft.Office.Interop.Excel.Worksheet worksheet = null; repExcel.Visible = false; repExcel.DisplayAlerts = false; object o = Missing.Value; //打开文件,n.FullPath是文件路径 workbook = repExcel.Application.Workbooks.Open(excelFileName, o, o, o, o, o, o, o, o, o, o, o, o, o, o); worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml; //进行另存为操作 workbook.SaveAs(rHtmlFilePath, ofmt, false, false, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, false, false, false, false, false); object osave = false; //逐步关闭所有使用的对象 workbook.Close(osave, o, o); repExcel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet); worksheet = null; //垃圾回收 GC.Collect(); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); workbook = null; GC.Collect(); System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel.Application.Workbooks); GC.Collect(); System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel); repExcel = null; GC.Collect(); //依据时间杀灭进程 System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("EXCEL"); foreach (System.Diagnostics.Process p in process) { if (DateTime.Now.Minute - p.StartTime.Minute > 1) { p.Kill(); } } Thread.Sleep(1000); }
嘿嘿~~,以上就是将excel转成html的方法。同时也可以通过该dll中的对象对excel进行写入文字和图片等功能。