object does not contain a definition for get_range

原因[1]

在VS2012中调用COM Interop DLL操作Excel通过get_Range去获取Range时,会发生Object does not contain a definition for get_Range的错误。其原因和解决方案:

Misha‘s
explanation is correct - when using No PIA, methods returning object
are treated as if they return dynamic in order to simulate the VBA
semantics of COM Variants. Because the return value of sh.Cells is
Object, sh.get_Range is dispatched dynamically, and the dynamic COM
binder does not support the get_Range syntax exposed in C# before
indexed properties were supported. We‘ve tried to maintain backwards
compatibility wherever possible when you turn on Embed Interop Types for
a COM reference, but this is one place where some further tweaking is
required.

The
workaround you proposed will work - a cleaner workaround is the one
Mike Rosenblum pointed out to use C# 4.0‘s new indexed properties
syntax, which the dynamic COM binder does understand. You can then
represent the operation with the following code:

Excel.Range r = sh.Range[sh.Cells[1, 1], sh.Cells[2, 2]];

See Also
get_Range method missing with embedded interop assembly

具体来讲[2]

由于Framework版本不同,因此支持的也不一样

例如:
在 .NET Framework 3.5 語法

Excel.Range r = sh.Range(sh.Cells[1, 1], sh.Cells[2, 2]);
在 .NET Framework 4.0-4.5 改用
Excel.Range r = sh.Range[sh.Cells[1, 1], sh.Cells[2, 2]];

winform导出Excel代码:

使用方法:    ExportExcel("条形码数据一览", GetSearchData);//GetSearchData可以传datatable 或者datagridview下面代码是传递Datatable的。

     /// <summary>
              /// 查询的数据导出为Excel
              /// </summary>
              /// <param name="fileName">导出文件名</param>
              /// <param name="myDGV">导出的datatable数据</param>
              private void ExportExcel(string fileName, MDataTable myDGV)
              {
                   string saveFileName = "";
                   SaveFileDialog saveDialog = new SaveFileDialog();
                   saveDialog.DefaultExt = "xls";
                   saveDialog.Filter = "Excel文件|*.xls";
                   saveDialog.FileName = fileName;
                   saveDialog.ShowDialog();
                   saveFileName = saveDialog.FileName;
                   if (saveFileName.IndexOf(":") < 0) return; //被点了取消
                   Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
                   if (xlApp == null)
                   {
                        MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
                        return;
                   }  

                   Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
                   Microsoft.Office.Interop.Excel.Workbook workbook =
     workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                   Microsoft.Office.Interop.Excel.Worksheet worksheet =
     (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1  

                   //写入标题
                   for (int i = 0; i < myDGV.Columns.Count; i++)
                   {
                        worksheet.Cells[1, i + 1] = myDGV.Columns[i].ColumnName;
                        //标题
                        Microsoft.Office.Interop.Excel.Range titleRange = worksheet.Range[worksheet.Cells[1, 1],
    worksheet.Cells[1, i + 1]];//选中标题
                        titleRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //水平居中
                   }
                   //写入数值
                   for (int r = 0; r < myDGV.Rows.Count; r++)
                   {
                        for (int i = 0; i < myDGV.Columns.Count; i++)
                        {
                             worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r][i].Value;
                             //设置边框
                             Microsoft.Office.Interop.Excel.Range allRange = worksheet.Range[worksheet.Cells[1, 1],
    worksheet.Cells[r + 1, i + 1]];
                             allRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                        }
                        System.Windows.Forms.Application.DoEvents();
                   }
                   //设置最后一行边框
                   Microsoft.Office.Interop.Excel.Range endRange = worksheet.Range[worksheet.Cells[1, 1],
    worksheet.Cells[myDGV.Rows.Count + 1,myDGV.Columns.Count]];
                   endRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                   worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
                   if (saveFileName != "")
                   {
                        try
                        {
                             workbook.Saved = true;
                             workbook.SaveCopyAs(saveFileName);
                        }
                        catch (Exception ex)
                        {
                             MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                        }  

                   }
                   xlApp.Quit();
                   GC.Collect();//强行销毁
                   MessageBox.Show("文件: " + fileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
              }

其他DataGridview导出Excel的资料:

http://www.360doc.com/content/11/1211/17/8147167_171489298.shtml  winform应用使用DataGridView数据导出到Excel

http://ruantnt.blog.163.com/blog/static/190525452201110185199346/  winform(c#) DataGridView导出Excel 
http://hi.baidu.com/wenshangang/item/1227f415fab1a35a2a3e229f  Winform中dataGridView控件导出到excel表格中

http://blog.sina.com.cn/s/blog_62cd5a980101905a.html  WinForm中DataGridView导出为Excel(快速版)

http://www.cr173.com/html/7906_1.html  WinForm下DataGridView导出Excel的实现

参考文章

1. [email protected] 原文地址 How to: 解决 Object does not contain a definition for get_Range.

2.kongwei521VS2013中Winform导出Excel文件时报“object”未包含“get_Range”的定义解决方法,2014-5.

时间: 2024-11-14 11:56:46

object does not contain a definition for get_range的相关文章

Page Object Manager

In last chapter of Page Object Pattern of Selenium Cucumber Framework, we learned how to design Page Object pattern using Selenium Page Factory in Cucumber. This chapter is again based on Page Objects. But in this chapter we will design a Page Object

JAVA XML

                                             JAVA     XML DOM 优缺点:实现 W3C 标准,有多种编程语言支持这种解析方式,并且这种方法本身操作上简单快捷,十分易于初学者掌握.其处理方式是将 XML 整个作为类似树结构的方式读入内存中以便操作及解析,因此支持应用程序对 XML 数据的内容和结构进行修改,但是同时由于其需要在处理开始时将整个 XML 文件读入到内存中去进行分析,因此其在解析大数据量的 XML 文件时会遇到类似于内存泄露以及

CMSIS OS None

/* ---------------------------------------------------------------------- * Copyright (C) 2011 ARM Limited. All rights reserved. * * $Date: 10. Februar 2012 * $Revision: V0.03 * * Project: CMSIS-RTOS API * Title: cmsis_os.h template header file * * V

Java中解析XML的四种方法

XML现在已经成为一种通用的数据交换格式,它的平台无关性,语言无关性,系统无关性,给数据集成与交互带来了极大的方便.对于XML本身的语法知识与技术细节,需要阅读相关的技术文献,这里面包括的内容有DOM(Document Object Model),DTD(Document Type Definition),SAX(Simple API for XML),XSD(Xml Schema Definition),XSLT(Extensible Stylesheet Language Transform

【Spring】@Transactional解释 (转)

Spring是当今广泛使用的框架,为Java核心堆栈带来了许多强大的功能和扩展.然而,大多数人倾向于使用这些功能,而不了解其潜在的机制. 由于现实生活中没有"魔法",我们将在这一系列文章中深入研究与事务和数据库相关的一些Spring功能. 第一篇文章是处理着名的@Transactional注释,为开发者节省了管理低级别事务代码的负担. 第二篇文章可以在这里:Spring @ PersistenceContext / @ PersistenceUnit解释 注意:以下代码分析使用Spri

Scala 访问修饰符(private-public-protected)

基本和Java的访问修饰符一样.在scala 中也有访问修饰符,如下 Members of packages, classes, or objects can be labeled with the access modifiers private and protected, and if we are not using either of these two keywords, then access will be assumed as public. These modifiers r

Data Types

原地址: Home / Database / Oracle Database Online Documentation 11g Release 2 (11.2) / Database Administration Data Types Each value manipulated by Oracle Database has a data type. The data type of a value associates a fixed set of properties with the va

《Distributed Programming With Ruby》读书笔记一Drb:Hellowold and Pass by Reference

<Distributed Programming With Ruby>Mark Bates Preface: The author was using Java and RMI(remote method invocation) as distributed interface in 2001. To solve performence problems, he found DRb. "I was already impressed with Ruby for being a ter

EXPDP IMPDP 知识总结

Data Pump Export ATTACH Default: job currently in the user's schema, if there is only one Purpose(目的) Attaches the client session to an existing export job and automatically places you in the interactive-command interface. Export displays a descripti