You can implement the VBA in .net
private void ConvertToExcel(string srcPath, string outputPath, XlFileFormat format)
{
if (srcPath== null) { throw new ArgumentNullException("srcPath"); }
if (outputPath== null) { throw new ArgumentNullException("outputPath"); }
var excelApp = new Application();
try
{
var wb = excelApp.Workbooks.Open(srcPath);
try
{
wb.SaveAs(outputPath, format);
}
finally
{
Marshal.ReleaseComObject(wb);
}
}
finally
{
excelApp.Quit();
}
}
You must install Microsoft.Office.Interop and add reference to a COM oject named Microsoft Excel XX.0 Object Library
Sample usage:
//generate excel file from the HTML output of GenerateHtml action.
var generateHtmlUri = new Uri(this.Request.Url, Url.Action("GenerateHtml"));
ConvertToExcel(generateHtmlUri.AbsoluteUri, @"D:\output.xlsx", XlFileFormat.xlOpenXMLStrictWorkbook);
I however discourage this solution because:
- You have to install MS Excel in your web server.
- MS Excel may sometimes misbehave like prompting a dialog box.
- You must find a way to delete the generated Excel file afterwards.
- Ugly design.
I suggest to generate excel directly because there doesn't seem to be better ways to covert HTML to Excel except using Excel itself or DocRaptor.