从Excel文件中读取数据

时间:2012-03-12 17:46:05

标签: c# interop

我在阅读C#中的Excel电子表格时遇到了一些麻烦。  我有这个代码,我从A到X读取每个单元格。

System.Array myvalues; string[] strArray;
Microsoft.Office.Interop.Excel.Range range = 
    worksheet.get_Range("A" + i.ToString(), "W" + i.ToString());

while(range.Count!=0)
{
    i++;
    //Console.WriteLine(i);
    range = worksheet.get_Range("A" + i.ToString(), "W" + i.ToString());
    myvalues = (System.Array)range.Cells.Value;
    strArray = ConvertToStringArray(myvalues);
    name = clearstr(strArray[1]);

    for ( int j = 1 ; j <= Int32.Parse(number_add_file)*4 ; j++) 
    {
        name = "";
        lang_add = "";
        price = "";
        description = "";
        Console.WriteLine("I got in!");

        Microsoft.Office.Interop.Excel.Range range_add = 
            worksheet.get_Range("X" + i.ToString(),Type.Missing);

        System.Array values = (System.Array)range_add.Cells.Value;
        string[] str = ConvertToStringArray(values);
        name = str[0];
        lang_add = str[1];
        price = str[2];
        description = str[3];
        Console.WriteLine(name + "   " 
          + lang_add + "   " + price + "   " + description);

        addfile();
    }

我的问题是:我怎样才能根据“数字”值读取excel中的下一个4 *“数字”行?

例如:

         A B C D E F G H I J
         a a a a a 1 a a a a 

F的单元格值是1所以我想阅读(G H I J) 如果F的单元格值为2,我想阅读(G H I J K L M N)

         A B C D E F G H I J K L M N
         a a a a a 2 a a a a a a a a

F的单元格值3:

        A B C D E F G H I J K L M N O P Q R
        a a a a a 3 a a a a a a a a a a a a

3 个答案:

答案 0 :(得分:2)

这适用于.NET 4.0:

using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("somefile.xls");
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1]; // assume it is the first sheet
Excel.Range xlRange = xlWorksheet.UsedRange; // get the entire used range
int value = 0;
if(Int32.TryParse(xlRange.Cells[1,6].Value2.ToString(), out value)) // get the F cell from the first row
{
   int numberOfColumnsToRead = value * 4;
   for(int col=7; col < (numberOfColumnsToRead + 7); col++)
   {
      Console.WriteLine(xlRange.Cells[1,col].Value2.ToString()); // do whatever with value
   }
}

这将打开工作簿并获取工作簿中的第一个工作表。然后我们得到整个使用范围并将其放在范围变量中。从那里,我们尝试在第一行中解析“F”列(这是第6列,它基于1而不是基于零)中的int。如果解析成功,我们然后将该数字乘以4以查看您需要多少列(在帖子中您说的是行,但您的示例是列)。我们使用for循环从G列开始(第7列)并转到要读取的列数+ 7(以考虑我们跳过的列)。您可以随意使用值来执行您想要的操作,但是对于此示例,我只是将它们写入控制台。

答案 1 :(得分:0)

这不是您问题的直接答案,但您可以轻松地参考您的单元格:

int row1 = 1;
int row2 = 5;

sheet1.Cells[row1, row1+row2].Value=row1.ToString();
String Rng = Convert.ToString(sheet1.Cells[row1, row2-row1].Address());

答案 2 :(得分:0)

string testList = "";
            String str1 = "";
            string logPath = @"E:\LogForConsoleApp.txt";
            string filePath = @"E:\SaveSheetName.txt";
            string Path = @"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\MSTest";
            List<string> ltSheetName = new List<string>();
            List<string> ltMethodName = new List<string>();
            Process myProcess = new Process();
            Excel.Application appExl = new Excel.Application();
            Excel.Workbook workbook = null;
            Excel.Worksheet NwSheet;
            Excel.Range ShtRange;
            appExl = new Excel.Application();
            workbook = appExl.Workbooks.Open("E:\\inputSheet3", Missing.Value, ReadOnly: false);
            NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
            ShtRange = NwSheet.UsedRange; //gives the used cells in sheet
            int rCnt = 0;
            int cCnt = 0;

            for (rCnt = 1; rCnt <= ShtRange.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt <= ShtRange.Columns.Count; cCnt++)
                {
                    if (Convert.ToString(NwSheet.Cells[rCnt, cCnt].Value2) == "Y")
                    {
                        ltSheetName.Add(NwSheet.Cells[rCnt, cCnt - 1].Value2);
                        //ltMethodName.Add(" /test:" + NwSheet.Cells[rCnt, cCnt - 1].Value2);
                    }
                }
            }
            workbook.Close(false, Missing.Value, Missing.Value);
            appExl.Quit();

            for (int sht = 0; sht < ltSheetName.Count; sht++)
            {
                ltMethodName.Clear();
                appExl = new Excel.Application();
                workbook = appExl.Workbooks.Open(ltSheetName[sht].ToString(), Missing.Value, ReadOnly: false);
                NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
                ShtRange = NwSheet.UsedRange; //gives the used cells in sheet
                int rCnt1 = 0;
                int cCnt1 = 0;

                for (rCnt1 = 1; rCnt1 <= ShtRange.Rows.Count; rCnt1++)
                {
                    for (cCnt1 = 1; cCnt1 <= ShtRange.Columns.Count; cCnt1++)
                    {
                        if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "Y")
                        {
                            ltMethodName.Add(" /test:" + NwSheet.Cells[rCnt, cCnt - 1].Value2);
                        }
                    }
                }
                workbook.Close(false, Missing.Value, Missing.Value);
                appExl.Quit();


                for (int i = 0; i < ltMethodName.Count; i++)
                {
                    str1 = ltMethodName[i].ToString();
                    testList += str1;
                }

                string foldername = "TestResult_" + DateTime.Today.ToString().Remove(DateTime.Today.ToString().LastIndexOf("/") + 5);
                foldername = foldername.Replace("/", "");

                string direc = @"E:\" + foldername;
                string fileName = ltSheetName[sht].ToString().Substring(ltSheetName[sht].ToString().LastIndexOf("\\") + 1) + "_InderdeepAutRes.trx";
                if (!Directory.Exists(direc))
                    Directory.CreateDirectory(direc);
                string testcase = "";

                if (!File.Exists(direc + "\\" + fileName))
                    testcase = " /testcontainer:" + "E:\\Practice\\TestingSample\\TestingSample\\bin\\Debug\\TestingSample.dll" + testList + " /resultsfile:" + direc + "\\" + fileName;
                else
                {
                    Directory.Delete(direc, true);
                    Directory.CreateDirectory(direc);
                    testcase = " /testcontainer:" + "E:\\Practice\\TestingSample\\TestingSample\\bin\\Debug\\TestingSample.dll" + testList + " /resultsfile:" + direc + "\\" + fileName;
                }

                ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(Path, testcase);

                try
                {
                    TextWriter tw = new StreamWriter(filePath, false);
                    tw.WriteLine(ltSheetName[sht].ToString());
                    tw.Close();
                    myProcess.StartInfo = myProcessStartInfo;
                    myProcessStartInfo.UseShellExecute = false;
                    myProcessStartInfo.RedirectStandardOutput = true;
                    myProcess.Start();
                    string output = myProcess.StandardOutput.ReadToEnd();
                    //myProcess.WaitForExit();
                    Console.WriteLine(output);

                }
                catch (Exception ex)
                {
                    TextWriter tw = new StreamWriter(logPath, true);
                    tw.WriteLine(ex.StackTrace);
                    tw.Close();
                }
            }