简体   繁体   English

C#按列索引读取Excel文件

[英]C# Reading an Excel file by column Index

I need to read an excel file using OLEDB by specifying column indexes. 我需要通过指定列索引来使用OLEDB读取Excel文件。 For an example I need to red data in Column A,B,C,AA,BC,ect... (the column indexes in Excel) 例如,我需要对A,B,C,AA,BC等列中的数据进行红色处理(Excel中的列索引)

How can Ido that? 我怎样才能做到这一点?

Thanks in advance. 提前致谢。

Did you tried a query like this SELECT A,B,C,AA,BC FROM Sheet1$ ? 您是否尝试过这样的查询: SELECT A,B,C,AA,BC FROM Sheet1$ Make sure you put Extended Properties="Excel 12.0;HDR=YES in the OLEDB connection string, it will help you to treat the first row as header. 确保在OLEDB连接字符串中放入Extended Properties="Excel 12.0;HDR=YES ,这将帮助您将第一行视为标题。

First just write a little function to convert A,B,C,AA... to 1,2,3,27,... Then use the numbered index to locate the column. 首先只需编写一个小函数即可将A,B,C,AA ...转换为1,2,3,27,...,然后使用编号索引找到该列。 There should be plenty of examples online to help you do this bit. 在线应该有很多示例可以帮助您做到这一点。

Thanushka, 塔努什卡,

I've used the excel 2007 openxml sdk ( DocumentFormat.OpenXml ) to great effect in this scenario. 在这种情况下,我使用了excel 2007 openxml sdk( DocumentFormat.OpenXml )产生了很大的效果。 It's basically a LINQ library that takes the excel docs into objects and allows you to query inside c# just like any other LINQ object. 它基本上是一个LINQ库,它将excel文档带入对象,并允许您像其他任何LINQ对象一样在c#中进行查询。 Microsoft actually do have (after a quick search) a pretty good 'idiots guide' on this topic. 微软实际上(在快速搜索之后)确实有关于该主题的相当不错的“白痴指南”。 You can find good resources here: 您可以在此处找到良好的资源:

http://msdn.microsoft.com/en-us/library/dd920313%28v=office.12%29.aspx http://msdn.microsoft.com/zh-cn/library/dd920313%28v=office.12%29.aspx

http://blogs.msdn.com/b/johnrdurant/archive/2010/02/19/excel-open-xml-linq-part-i.aspx http://blogs.msdn.com/b/johnrdurant/archive/2010/02/19/excel-open-xml-linq-part-i.aspx

http://www.briankeating.net/blog/post/2010/04/26/Linq-to-Xlsx.aspx http://www.briankeating.net/blog/post/2010/04/26/Linq-to-Xlsx.aspx

if you use LINQ, it's a no-brainer and is definitely the only way that I would go with this type of task. 如果您使用LINQ,那将是一件容易的事,并且绝对是我执行此类任务的唯一方法。 For me, it's much more intuitive to use practices akin to the way that other objects are used in your application and thus this LINQ approach works well if that's your bag. 对我来说,使用类似于在您的应用程序中使用其他对象的方式的做法要直观得多,因此,如果您愿意的话,这种LINQ方法就可以很好地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM