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

RAMAN RAGAVAN 51 Reputation points
2021-12-14T12:51:28.837+00:00

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);

      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();

    }
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-12-14T15:33:51.35+00:00

    My recommendation is to avoid Excel automation and use a library such as SpreadSheetLight (free)

    Simple starter code

    public static void Example(string fileName, string sheetName)  
    {  
        using (var document = new SLDocument(fileName, sheetName))  
        {  
            var stats = document.GetWorksheetStatistics();  
            for (int rowIndex = 1; rowIndex < stats.EndRowIndex + 1; rowIndex++)  
            {  
                for (int columnIndex = 1; columnIndex < stats.EndColumnIndex +1; columnIndex++)  
                {  
                    Console.WriteLine($"{SLConvert.ToCellReference(rowIndex, columnIndex)} = {document.GetCellValueAsString(rowIndex, columnIndex)}");  
                }  
            }  
        }  
    }  
    

    157479-figure1.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.