使用Microsoft.Office.Interop.Excel从CSV读取 [英] Reading from CSV using Microsoft.Office.Interop.Excel

查看:298
本文介绍了使用Microsoft.Office.Interop.Excel从CSV读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在尝试使用Microsoft.Office.Interop.Excel从CSV文件加载数据。



这是我正在使用的代码:



Hi,

I'm trying to load data from a CSV file using Microsoft.Office.Interop.Excel.

Here is the code I'm using:

List<string> lstColumnsNames = new List<string>();

                    Microsoft.Office.Interop.Excel.Application objExcelApplication = new Microsoft.Office.Interop.Excel.Application();

                    objExcelApplication.Workbooks.OpenText(strFilePath,
                                                        DataType: Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited,
                                                        TextQualifier: Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierNone,
                                                        ConsecutiveDelimiter: true,
                                                        Semicolon: true);

                    Microsoft.Office.Interop.Excel.Worksheet objExcelWorksheet = objExcelApplication.Workbooks[1].Sheets[strTableName];

                    if (objExcelWorksheet != null)
                    {
                        int columnCount = objExcelWorksheet.UsedRange.Columns.Count;
                        for (int i = 1; i < columnCount + 1; i++)
                        {
                            if (objExcelWorksheet.Cells[1, i].Value != null)
                            {
                                if (!lstColumnsNames.Contains(objExcelWorksheet.Cells[1, i].Value.ToString()))
                                    lstColumnsNames.Add(objExcelWorksheet.Cells[1, i].Value.ToString());
                            }
                        }
                    }

                    objExcelApplication.Workbooks[1].Close();





当我加载一个csv作为扩展名的文件时,它并没有按照分号真正分开(虽然它应该是指定的) 。但是当同一个文件保存为文本文件时,确实如此。



是否有遗漏的东西?



提前致词并提前致谢。



When I do load a file having a csv as extension, it does not really separate according to semicolons (while it is specified it should be). but when the same file is saved as a text file, it does.

Is there something missing?

Regards and thanks in advance.

推荐答案

您可能会遗漏某些属性,因为您的代码根据您的预期无法正常工作。但是,如果您认为您没有错过任何属性并且代码在csv文件的情况下无法正常工作,那么我认为在将该文件传递给csv之前将csv文件的扩展名更改为txt文件并不是一个坏主意。这种方法。
You may be missing some property due to which your code is not working as per your expectation. But if you think you haven't missed any property and the code is not working properly in case of csv file then I don't think it is a bad idea to change the extension of csv file to txt file before you pass that file to this method.


这篇关于使用Microsoft.Office.Interop.Excel从CSV读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆