使用C#将excel范围转换为数组 [英] convert excel range to array using C#

查看:837
本文介绍了使用C#将excel范围转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C#将excel范围转换为数组

I want to convert excel range to array using C#

System.Array MyRange = (System.Array)range.cells.value;
    for (int k = 0; k <= MyRange.Length; k++)
    {
        List<service_name> _ml = new List<service_name>();
        for (int j = 1; j < dataitems.Count; j++)
        {
            // enter code here
        }
    }

如何迭代循环
但是这个代码不起作用,并且调用错误:

how to iterate in loop but this code not work and invoke error:


无法将类型为System.Array的对象转换为System.Array。

"Unable to cast object of type 'System.String' to type 'System.Array'."


推荐答案

根据帮助,我的Microsoft 这里,这是我在Excel中读取和写入数组的方式。

Based on the help provided my Microsoft here, this is how I read and write an array in Excel.

var xlApp=new Microsoft.Office.Interop.Excel.Application();
var wb=xlApp.Workbooks.Open(fn, ReadOnly: false);
xlApp.Visible=true;
var ws=wb.Worksheets[1] as Worksheet;
var r=ws.Range["A2"].Resize[100, 1];
var array=r.Value;
// array is object[1..100,1..1]
for(int i=1; i<=100; i++)
{
    var text=array[i, 1] as string;
    Debug.Print(text);
}
// to create an [1..100,1..1] array use
var array2=Array.CreateInstance(
    typeof(object), 
    new int[] {100, 1}, 
    new int[] {1, 1}) as object[,];

// fill array2
for(int i=1; i<=100; i++)
{
    array2[i, 1] = string.Format("Text{0}",i);
}
r.Value2=array2;

wb.Close(SaveChanges: true);
xlApp.Quit();


这篇关于使用C#将excel范围转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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