//Change the Source File's Extension to ".xml" because we are about to use OpenXML method in this function. You can even use Open() method for .txt, .csv, etc files.
//This function takes an "xml" file (even if the contents in the file are html/csv contents) and converts into a Binary Excel File.
//Idea is very simple, Open a file and Save As a binary file.
public void ExportToExcel(){
try
{
string xmlFile = "C:\\test.xml";string xlsFile = "C:\\test.xls";
Microsoft.Office.Interop.Excel.Application oApp = new Microsoft.Office.Interop.Excel.Application();System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("Excel");
System.Diagnostics.Process currentProcess = processes[processes.Length - 1];//Get the Last Excel process just created (a bit tricky)oApp.DisplayAlerts = false;
object obj = oApp.Workbooks.OpenXML(xmlFile, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
object[] para = new object[12];object fileName = xlsFile;
object fileFormat = Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel5;object missing = System.Reflection.Missing.Value;
object fileMode = Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive;para[0] = fileName;
para[1] = fileFormat;
para[2] = missing;
para[3] = missing;
para[4] = missing;
para[5] = missing;
para[6] = fileMode;
para[7] = missing;
para[8] = missing;
para[9] = missing;
para[10] = missing;
para[11] = missing;
Type MyType = (Type)(obj.GetType());MyType.GetMethod("SaveAs").Invoke(obj, para);oApp.Workbooks.Close();
oApp.Quit();
currentProcess.Kill();
}
catch (Exception ex){
throw ex;}
}
No comments:
Post a Comment