如何查找ExcelInterop中的第一个和最后一个单元格以及C#中的图形范围 [英] How to find first and last cell in ExcelInterop and graph range in C#

查看:171
本文介绍了如何查找ExcelInterop中的第一个和最后一个单元格以及C#中的图形范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图在Excel中绘制一个简单的csv文件:

Trying to graph a simple csv file in Excel :

1,2,3
4,5,6
7,8,9

如何以编程方式将图形范围确定为A1 :C3?

How do I programmatically determine the graphing range to be A1:C3?

我尝试过

            var lastCell = worksheet.Cells.get_End(XlDirection.xlUp);

确定最后一列,但似乎不起作用。

to determine the final column but it doesn't seem to work.

以下是我用来绘制文件的代码,我只需要确定范围。

The following is the code that I am using to graph the file, and I just need to determine the range.

using Microsoft.Office.InteropServices.Excel;



        Application application = new Application();
        Workbook workbook = application.Workbooks.Open(fileName);
        var worksheet = workbook.Worksheets[1] as
            Microsoft.Office.Interop.Excel.Worksheet;


                   // Add chart.
        var charts = worksheet.ChartObjects() as
            Microsoft.Office.Interop.Excel.ChartObjects;
        var chartObject = charts.Add(60, 10, 300, 300) as
            Microsoft.Office.Interop.Excel.ChartObject;
        var chart = chartObject.Chart;

        // Set chart range.
        var range = worksheet.get_Range( ); //  ????????
        chart.SetSourceData(range);

        // Set chart properties.
        chart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlLine;
        chart.ChartWizard(Source: range,
            Title: graphTitle,
            CategoryTitle: xAxis,
            ValueTitle: yAxis);


        // Save.
        workbook.Save();
        workbook.Close();


推荐答案

您可以尝试以这种方式获取您的范围:

You can try to get your range in this way:

var range = worksheet.get_Range("A1", System.Type.Missing).CurrentRegion;

获取从单元格A1开始的范围,直到创建范围连续区域的最后一个单元格。我认为这是使用CSV文件时的最佳选择。

It gets the range which starts as of cell A1 until the last cell which make a range continuous area. I think this will be best option when working with CSV file.

根据 MSDN(VBA)


(CurrentRegion)返回表示当前区域的Range对象。当前的
区域是空白行和空白
列的任意组合的范围。

(CurrentRegion) Returns a Range object that represents the current region. The current region is a range bounded by any combination of blank rows and blank columns.

这篇关于如何查找ExcelInterop中的第一个和最后一个单元格以及C#中的图形范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆