c#在excel中添加超链接示例分享
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();
}
}
}
上一篇: c# xml API操作的小例子