欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#在excel中添加超链接示例分享

程序员文章站 2024-02-23 20:02:04
1.新建一个项目 2.给项目添加引用:microsoft excel 12.0 object library (2007版本) 复制代码 代码如下:using exce...

1.新建一个项目

2.给项目添加引用:microsoft excel 12.0 object library (2007版本)

复制代码 代码如下:

using excel = microsoft.office.interop.excel;

3.对excel的简单操作:如下代码“添加超链接”等。

复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using excel = microsoft.office.interop.excel;

namespace excelexample
{
    class program
    {
        static void main(string[] args)
        {
            excel.application excelapp = new excel.application();  // creates a new excel application
            excelapp.visible = true;  // makes excel visible to the user.

            // the following line if uncommented adds a new workbook
            //excel.workbook newworkbook = excelapp.workbooks.add();

            // the following code opens an existing workbook
            string workbookpath = "f:\\11.xlsx";  // add your own path here

            excel.workbook excelworkbook = null;

            try
            {
                excelworkbook = excelapp.workbooks.open(workbookpath, 0,
                    false, 5, "", "", false, excel.xlplatform.xlwindows, "", true,
                    false, 0, true, false, false);
            }
            catch
            {
                //create a new workbook if the existing workbook failed to open.
                excelworkbook = excelapp.workbooks.add();
            }

            // the following gets the worksheets collection
            excel.sheets excelsheets = excelworkbook.worksheets;

            // the following gets sheet1 for editing
            string currentsheet = "sheet1";
            excel.worksheet excelworksheet = (excel.worksheet)excelsheets.get_item(currentsheet);

            // the following gets cell a1 for editing
            excel.range excelcell = (excel.range)excelworksheet.get_range("a1", "b1");

            // the following sets cell a1's value to "hi there"
            excelcell.value2 = "hi there";

            excel.worksheet excelworksheet2 = (excel.worksheet)excelsheets.get_item("sheet2");
            excel.range excelcell2 = (excel.range)excelworksheet2.get_range("a1", type.missing);
            excelcell2.value2 = "hi here";

            // add hyperlinks to the cell a1
            //excelworksheet.hyperlinks.add(excelcell,"http:\\www.baidu.com",type.missing,"baidu",type.missing);

            // add hyperlinks from "sheet1 a1" to "sheet2 a1"
            excelworksheet.hyperlinks.add(excelcell, "#sheet2!a1", type.missing, type.missing, type.missing);

            // close the excel workbook
            //excelworkbook.close(true,type.missing,type.missing);

            //quit the excel app
            //excelapp.quit();
        }
    }
}