Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

c# - Extracting a URL from hyperlinked text in Excel cell

I have a table full of Hyperlinked text in excel, so it's basically a bunch of names but when I click on one, it takes me to some URL in my default browser.

So I am extracting text from this excel table in my program, but the value I get when I extract from these hyperlink cells is that of the string inside, when I want the URL the string is linked to in the excel file.

So I'm thinking there are two ways to do this. Either I can convert all the hyperlinked text in the excel file to the corresponding URLs, or I can use C# to somehow extract the URL value from the cell and not the text.

I don't know how to do either of these things, but any help would be greatly appreciated.

C# code so far:

Excel.ApplicationClass excelApp = new Excel.ApplicationClass();

//excelApp.Visible = true;

Excel.Workbook excelWorkbook = 
excelApp.Workbooks.Open("C:\Users\use\Desktop\list.xls",
0, false, 5, "", "",false, Excel.XlPlatform.xlWindows, "", 
true, false, 0, true, false, false);

Excel.Sheets excelSheets = excelWorkbook.Worksheets;

string currentSheet = "Sheet1";
Excel.Worksheet xlws = (Excel.Worksheet)excelSheets.get_Item(currentSheet);

string myString = ((Excel.Range)xlws.Cells[2, 1]).Value.ToString();

As for the excel file, it's just one long row of names hyperlinked. For instance cell A2 would contain the text:

Yummy cookie recipe

And I want to extract the string:

http://allrecipes.com//Recipes/desserts/cookies/Main.aspx
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a vba macro:

Hit Alt+F11 to open the VBA editor and paste in the following:

Function URL(rg As Range) As String
  Dim Hyper As Hyperlink
  Set Hyper = rg.Hyperlinks.Item(1)
  URL = Hyper.Address
End Function

And then you can use it in your Worksheet, like this:

=URL(B4)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...