我需要使用Excel文件中的信息填充数组

时间:2018-04-23 09:53:31

标签: c# excel

阵列是二维的。我能够从excel文件中读取信息。我已经完成了很多事情;但我无法弄清楚如何编写代码来填充我创建的数组。我不能硬编码数据,因为有超过两个2000条目。我需要数组,所以我可以使用excel文件中的信息插入我程序其余部分的公式。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using System.Reflection;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;

            string str;
            int rCnt;
            int cCnt;
            int rw = 0;
            int cl = 0;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open(@"D:\data.csv", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;
            rw = range.Rows.Count;
            cl = range.Columns.Count;

            decimal[,] coords = new decimal[2207,2];


            for (rCnt = 1; rCnt <= rw; rCnt++)
            {
                for (cCnt = 1; cCnt <= cl; cCnt++)
                {

                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我会选择:

rw = range.Rows.Count;
cl = range.Columns.Count;

decimal[,] coords = new decimal[rw,cl]; // not hardcoded size

for (rCnt = 1; rCnt <= rw; rCnt++)
{
    for (cCnt = 1; cCnt <= cl; cCnt++)
    {
        coords[rCnt-1, cCnt-1] = xlWorkSheet.Cells[rCnt, cCnt].Value;
    }
}

请注意,如果您的两列相关,则可以执行以下操作:

public class Coord
{
    public decimal X {get;set;}
    public decimal Y {get;set;}
}

然后:

rw = range.Rows.Count;

List<Coord> coords = new List<Coord>();

for (rCnt = 1; rCnt <= rw; rCnt++)
{
    coords.Add(new Coord
    {
        X = xlWorkSheet.Cells[rCnt, 1].Value,
        Y = xlWorkSheet.Cells[rCnt, 2].Value,
    });
}