How to find first and last cell in ExcelInterop and graph range in C#

杀马特。学长 韩版系。学妹 提交于 2019-12-24 01:44:52

问题


Trying to graph a simple csv file in Excel :

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

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

I have tried

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

回答1:


You can try to get your range in this way:

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

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.

According to MSDN (VBA):

(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.



来源:https://stackoverflow.com/questions/18293227/how-to-find-first-and-last-cell-in-excelinterop-and-graph-range-in-c-sharp

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