Sujeet Raman

Sujeet Raman

  • 869
  • 927
  • 354.6k

How to get specific Rows count and value from an excel sheet tab 3

Dec 14 2021 12:48 PM

Hi, i have to get datas from 3rd colom of 3rd tab in an excel sheet.For all 3 tabs i have same number of rows.So when i tried to copy 3rd colom data always copying first colom data.I need to save only colom 3 value and heading save in to .txt file.How can i get 3rd clm data with heading?

I need to use interop

Excel._Worksheet xlWorksheetA = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Sheets[3];

               Excel.Range firstColumnA = (Excel.Range)xlWorksheetA.UsedRange.Columns[3];

               int RowsA = firstColumnA.Rows.Count;

                int ColumnsA = firstColumnA.Columns.Count;

                MessageBox.Show("RowsA"+RowsA); MessageBox.Show("ColumnsA"+ColumnsA);

               Createtextfile(RowsA, ColumnsA, xlWorksheetA);


//creating txt file from 3rd clm data


public static void Createtextfile(int lastUsedRow, int lastUsedColumn, Excel._Worksheet xlWorksheet)

        {
            string output = "";
            string ExportPath = mypath;


            for (int i = 1; i <= lastUsedRow; i++)
            {
                for (int j = 1; j <= lastUsedColumn; j++)

                {
                    object xVal = ((Excel.Range)xlWorksheet.Cells[i, j]).Value;

                    if (xVal != null)

                    {

                        output += xVal.ToString();

                    }


                    output += Environment.NewLine;

                }
            }


            FileStream fs = new FileStream(ExportPath, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(fs);
            writer.Write(output);
            writer.Close();
        
        }

 


Answers (2)