Interop Excel UsedRange Rows Count incorrect

断了今生、忘了曾经 提交于 2020-01-11 06:37:08

问题


I am trying to read an excel spreadsheet into memory but when I use worksheet.UsedRange.Rows.Count, the value return is incorrect. I have 1670 rows of data in my spreadsheet but the row count brings back 694 rows.

var excelApp = new Microsoft.Office.Interop.Excel.Application {Visible = false};
var workbook = excelApp.Workbooks.Open(_mirrorFileName,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing);

var worksheet = (Worksheet)workbook.Worksheets[1];
var excelRange = worksheet.UsedRange;            
var valueArray = (object[,])excelRange.Value[XlRangeValueDataType.xlRangeValueDefault];

var rowCount = worksheet.UsedRange.Rows.Count;

Should I be using UsedRange to find the row count or is there another method???


回答1:


Try the following sample code,

using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel; 

namespace WindowsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp ;
        Excel.Workbook xlWorkBook ;
        Excel.Worksheet xlWorkSheet ;
        Excel.Range range ;

        string str;
        int rCnt = 0;
        int cCnt = 0;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        range = xlWorkSheet.UsedRange;

        rCnt = range.Rows.Count;
        cCnt = range.Columns.Count;

        xlWorkBook.Close(true, null, null);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);
    }
}

Declare variable Excel.Range range and then use it.



来源:https://stackoverflow.com/questions/24264321/interop-excel-usedrange-rows-count-incorrect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!