怎么用C#将txt文件的转换成excel文件,txt每格数据用逗号隔开,转换成功后也分别插入excel 中每一格中。

2024-11-30 05:54:21
推荐回答(2个)
回答1:

不知道下面的代缓纯码能不能帮旁哪轮到你,你可以运信试试看

// Open the text file in Excel.
m_objExcel = new Excel.Application();
m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
m_objBooks.OpenText(m_strSampleFolder + "Book6.txt", Excel.XlPlatform.xlWindows, 1,
Excel.XlTextParsingType.xlDelimited, Excel.XlTextQualifier.xlTextQualifierDoubleQuote,
false, true, false, false, false, false, m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt);

m_objBook = m_objExcel.ActiveWorkbook;

// Save the text file in the typical workbook format and quit Excel.
m_objBook.SaveAs(m_strSampleFolder + "Book6.xls", Excel.XlFileFormat.xlWorkbookNormal,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt,
m_objOpt, m_objOpt);
m_objBook.Close(false, m_objOpt, m_objOpt);
m_objExcel.Quit();

回答2:

以微软的office为例(电脑中必须安装有office excel):
你会用c#把txt文件的内容读出来吗?
如果不会看一下 StreamReader 类

读出来以后,在项目中添加引用,选.NET中的Microsoft.Office.Interop.Excel
再看一下 该命名空间下的类:Application,_Workbook,Sheets,_Worksheet,Range
最后一定要手动清理资源。雀丛迅
我只把清理资源的代码贴郑迟上:
book_excel.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
System.Runtime.InteropServices.Marshal.ReleaseComObject(range_excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets_excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book_excel);
excel_1.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel_1);
祝你好运。顷此