如何通过Excel工作表的特定列仅提取数据迭代 [英] How to iterate through Excel Worksheets only extracting data from specific columns

查看:219
本文介绍了如何通过Excel工作表的特定列仅提取数据迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过Excel工作簿与多个工作表只能从提取数据迭代说列C,E和放大器; F?

How do you iterate through an excel workbook with multiple worksheets only extracting data from say columns "C", "E" & "F"?

下面是code我迄今:

Here is the code I have thus far:

public static string ExtractData(string filePath)
    {
        Excel.Application excelApp = new Excel.Application();
        Excel.Workbook workBook = excelApp.Workbooks.Open(filePath);

        string data = string.Empty;

        int i = 0;
        foreach (Excel.Worksheet sheet in workBook.Worksheets)
        {
            data += "*******   Sheet " + i++.ToString() + "   ********\n";

            //foreach (Excel.Range row in sheet.UsedRange.Rows)
            //{
            //    data += row.Range["C"].Value.ToString();
            //}

            foreach (Excel.Range row in sheet.UsedRange.Rows)
            {
                foreach (Excel.Range cell in row.Columns)
                {
                    data += cell.Value + "   ";
                }
                data += "\n";
            }
        }

        excelApp.Quit();

        return data;
    }

非常感谢您的宝贵时间,任何帮助是AP preciated。

Thank you very much for your time, any help is appreciated.

推荐答案

编辑你的方法,这里的东西应该做的,你在找什么:

Editing your method, here's something should do what you're looking for:

public static string ExtractData(string filePath)
{
    Excel.Application excelApp = new Excel.Application();
    Excel.Workbook workBook = excelApp.Workbooks.Open(filePath);
    int[] Cols = { 3, 5, 6 }; //Columns to loop
                 //C, E, F
    string data = string.Empty;

    int i = 0;
    foreach (Excel.Worksheet sheet in workBook.Worksheets)
    {
        data += "*******   Sheet " + i++.ToString() + "   ********\n";

        foreach (Excel.Range row in sheet.UsedRange.Rows)
        {
            foreach (int c in Cols) //changed here to loop through columns
            {
                data += sheet.Cells[row.Row, c].Value2.ToString() + "   ";
            }
            data += "\n";
        }
    }

    excelApp.Quit();

    return data;
}

我创建了一个int数组,指示其列,你想从阅读,然后在每个行,我们通过阵列只是循环。

I've created a int array to indicate which columns you'd like to read from, and then on each row we just loop through the array.

心连心, ž

这篇关于如何通过Excel工作表的特定列仅提取数据迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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