Opening .dat (tab delimited file) in Excel, save as .xls

匆匆过客 提交于 2020-02-14 19:28:13

问题


I am trying to open a .dat file in Excel, which is tab delimited, and then have it save out as a .xls file.

So far, I can read in the file and save it as the .xls file but for some reason, all the values are in the first column and it does not tab delimit them.

(If I open up the file in Excel without my program, it tab-delimits perfectly)

These are the two lines of code that I am using to open and resave the file.

xlWorkBook = xlApp.Workbooks.Open(f, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);  
xlWorkBook.SaveAs(filename + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

回答1:


I don't use C#, but I'm thinking you might need to use something like Workbooks.OpenText method detailed here: http://msdn.microsoft.com/en-us/library/bb223513%28v=office.12%29.aspx

It allows you to specify delimiters, etc.

Something like this:

xlWorkBook = xlApp.Workbooks.OpenText (filename:="DATA.TXT", dataType:=xlDelimited, tab:=True);

That's from the Excel 2007 Developer reference, but maybe there's a similar method in C#? Just a guess.




回答2:


The fix for this question:

xlWorkBook = xlApp.Workbooks.Open(f, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkBook.SaveAs(filename + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

In the xlApp.Worksbooks.Open() method, the fourth arg is "Format" which if you use the value '1', it will assume that the file is tab delimited and open it accordingly.




回答3:


How about using FileHelpers ?

I have used this approach a lot, and find it a super nice library.

It handles delimited and fixed length files, and you can write back to Excel using the ExcelStorage class.




回答4:


This sould work:

using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office;
using Microsoft.Office.Core;

        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlApp = new Excel.Application();
        xlApp.Workbooks.OpenText(@"c:\data.txt", Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited);
        xlApp.Visible = true;


来源:https://stackoverflow.com/questions/9588223/opening-dat-tab-delimited-file-in-excel-save-as-xls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!