using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace SettlementResolve { public partial class JDSettlement : Form { public JDSettlement() { InitializeComponent(); } private void txtbox_ReadOnlyChanged(object sender, EventArgs e) { txtbox.ReadOnly = true; } private void JDSettlement_Load(object sender, EventArgs e) { } /// <summary> /// 將.csv文件轉換成.xlsx文件 /// </summary> /// <param name="FilePath">.csv文件絕對路徑</param> /// <returns>返回轉換后的.xlsx文件路徑</returns> public static string CSVSaveasXLSX(string FilePath) { QuertExcel(); string NewFilePath = ""; Excel.Application excelApplication; Excel.Workbooks excelWorkBooks = null; Excel.Workbook excelWorkBook = null; Excel.Worksheet excelWorkSheet = null; try { excelApplication = new Excel.Application(); excelWorkBooks = excelApplication.Workbooks; excelWorkBook=((Excel.Workbook) excelWorkBooks.Open(FilePath,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value, Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value)); excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets[1]; excelApplication.Visible = false; excelApplication.DisplayAlerts = false; NewFilePath = FilePath.Replace(".csv", ".xlsx"); excelWorkBook.SaveAs(NewFilePath, Excel.XlFileFormat.xlAddIn, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); excelWorkBook.Close(); QuertExcel(); GC.Collect(System.GC.GetGeneration(excelWorkSheet)); GC.Collect(System.GC.GetGeneration(excelWorkBook)); GC.Collect(System.GC.GetGeneration(excelApplication)); } catch (Exception exc) { throw new Exception(exc.Message); } finally { GC.Collect(); } return NewFilePath; } /// <summary> /// 執行過程中可能會打開多個EXCEL文件,所以Kill掉 /// </summary> private static void QuertExcel() { Process[] excels = Process.GetProcessesByName("EXCEL"); foreach (var item in excels) { item.Kill(); } } } }
原文轉載自:http://www.cnblogs.com/junjie94wan/archive/2013/05/23/3094483.html
原文有個地方被我修改過來,在CSVSaveasXLS方法中
excelApplication = new Excel.ApplicationClass();
這行會出現以下的問題:
導致整個程序無法運行,所以我稍作修改成我以上所寫的代碼,運行調試后,暫無發現明顯問題。