简体   繁体   中英

Reading an entire row from a .xls/.xlsx file with c#

Im trying to read a .xls/.xlsx file using ac# program I am using excel interop. However I can only read 1 cell at a time. Can someone show me how to read an entire row and put it inside a string?

This is my code so far:

Excel.Application xlApp = new Excel.Application();

                Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Path.GetFullPath("C:\\..\\A1.xlsx"));

                Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);

                Excel.Range xlRange = xlWorksheet.UsedRange;
string temp = (string)(xlRange.Cells[1,2] as Excel.Range).Value2;
              Console.WriteLine(temp);

What you have written so far is perfect. Just try and execute the temp in loop and get values for each cells as below

for (rCnt = 1; rCnt <= xlRange.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt <= xlRange.Columns.Count; cCnt++)
                {
                    string temp = (string)(xlRange.Cells[rCnt,Ccnt] as Excel.Range).Value2;
                    Console.WriteLine(temp);
                }
            }

I guess this will solve your purpose, of getting individual cells and stroing it in the string

For reading entire rows you can keep the row value constant and iterate the columns and store it in an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM