做项目中需要用到一个将excel转html的功能,百度了半天,找到了忘了哪个小可爱提供的方法,即,利用excel自带的另存为的功能,保存成html文件,保存是可以实现,但是保存完之后查看电脑任务管理器,发现有office进行未退出,一直占用资源,造成服务器经常卡顿,因此进行了修改,采用保存完强制杀死进程的方法,解决了资源释放的问题。
public static void Excel2Html(string path, string savePath, string wordFileName)
{
//清空文件
if (Directory.Exists(savePath))
DeleteDir(savePath);
else
Directory.CreateDirectory(savePath);
string str = string.Empty;
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;
object osave = true;
try
{
workbook = repExcel.Application.Workbooks.Open(path, 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);
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
object htmlFile = savePath + wordFileName + ".html";
object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
workbook.SaveAs(htmlFile, ofmt, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
osave = false;
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
if (workbook != null)
{
workbook.Close(true, Type.Missing, Type.Missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
}
repExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel);
IntPtr t = new IntPtr(repExcel.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill();
}
}
有需要的小可爱可以参考,有什么问题可以交流。。