使用 LINQ to SQL 查询中的数据填充 Excel
我正在尝试使用 OLE 将一些数据从 C# 中的 LINQ 查询发送到 Excel 速度表
我有这样的查询:
Var data = from d in db.{MyTable}
where d.Name = "Test"
select d;
我有 Excel OLE 对象工作正常,我只是不知道如何填充 Excel 中的单元格使用来自 LINQ 查询的数据。
PS:如果这有什么区别的话,我正在使用 Excel 2003。
谁能帮我这个?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为每个 Excel 单元格发送单独的 OLE 命令非常慢,因此关键是创建一个如下所示的对象数组:
发送对象数组允许您发送混合数据类型,例如字符串、整数、日期等。但是,如果您知道例如,数据都是文本,您可以只发送字符串数组。
需要通过分配每个单独的值或通过使用反射来获取数据对象属性来从查询填充该数组。 然后您可以将数组发送到 Excel,如下所示:
您可以用列数替换 Z20 -> 字符+行数-> 细绳。
Sending individual OLE commands for each Excel cell is very slow so the key is to create an object array like this:
Sending an object array allows you to send a mixture of data types e.g. string, integer, date etc. However, if you know that the data is all text for example, you can just send a string array.
The array needs to be populated from the query either by assigning each individual value or perhaps by using reflection to get the data object properties. Then you can send the array to Excel like this:
You can substitute Z20 with the number of columns -> Char + the number of rows -> string.
我假设您没有在 Web 场景中使用 OLE,因为它最终会失败。
如果您只需要原始数据,可以转储到制表符分隔的文本文件:
varlines = data.Select(d => d.Name + '\t' + d.AnotherProperty + ...);
I assume you are not using OLE in a web scenario, because it will eventually fail.
If you just need raw data, you can dump to a tab-delimited textfile:
var lines = data.Select(d => d.Name + '\t' + d.AnotherProperty + ...);
最佳选择是使用 Excel XML 格式。 我写了一篇关于如何实现这一目标的博客文章: http://www.aaron -powell.com/blog.aspx?id=1237
您的另一个选择是查看 Excel 的 LINQ 提供程序 - http://www.codeplex.com/xlslinq。
Your best option is using the Excel XML format. I did a blog post on how to achieve that: http://www.aaron-powell.com/blog.aspx?id=1237
You're other option would be looking at the LINQ provider for Excel - http://www.codeplex.com/xlslinq.