Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
732 views
in Technique[技术] by (71.8m points)

c# - How to iterate through Excel Worksheets only extracting data from specific columns

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

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() + "   ********
";

            //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 += "
";
            }
        }

        excelApp.Quit();

        return data;
    }

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() + "   ********
";

        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 += "
";
        }
    }

    excelApp.Quit();

    return data;
}

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.

HTH, Z


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...