本文介绍了Interop Excel UsedRange行数不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将excel电子表格读入内存,但是当我使用worksheet.UsedRange.Rows.Count时,返回值不正确.电子表格中有1670行数据,但行数却带回694行.

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;

我应该使用UsedRange查找行数还是有另一种方法?

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

推荐答案

尝试以下示例代码,

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

声明变量Excel.Range range,然后使用它.

Declare variable Excel.Range range and then use it.

这篇关于Interop Excel UsedRange行数不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 08:04