我有一个非常大的excel文件,我们必须在数据库中导入。导入工作正常,但导入它需要35秒。客户不能等待太多。我在其中创建了书签。
以下是创建书签的链接。 http://www.youtube.com/watch?v=9n4g_l7h8jc
现在我想从C#代码中读取这些书签。正如我所说,我们有不同的部分,如:
1.分配
2.工作人员
3.资源
4.预算等......
我可以直接从此代码访问此标题/部分,我正在获取行和列
_Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Range xlRange = xlWorksheet.UsedRange;
var externalDprDistribution = xlRange.Find("Distribution");
var colDist = externalDprDistribution.Column;
var rowDist = externalDprDistribution.Row;
但我仍然想在Excel工作表中创建书签,然后我想访问c#代码中的书签,并从那里获得行和列。所以我需要一个可以在c#
中访问创建的书签的代码有任何帮助吗? 此致
答案 0 :(得分:0)
如果你提取Excel文件,你会发现书签是超链接。
<hyperlinks>
<hyperlink ref="G18" location="Test_Mark1" display="Bookmark1"/>
<hyperlink ref="G10" r:id="rId1"/>
</hyperlinks>
最近对于一个项目,我写了下面的测试代码来查找书签并更新它们,希望它有所帮助
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.IO.Packaging;
using System.Xml;
using System.IO;
namespace OpenXMLTest
{
class Program
{
static void Main(string[] args)
{
string fileName = @"c:\temp\book1.xlsx";
Console.WriteLine("Start reading bookmark of excel...");
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fs, true))
{
WorkbookPart workbookPart = doc.WorkbookPart;
//find bookmarks
foreach (var workSheetPart in workbookPart.WorksheetParts)
{
var temp = workSheetPart.RootElement.Descendants<Hyperlinks>();
IEnumerable<Hyperlink> hyperLinks = null;
if (temp.Count() > 0)
{
hyperLinks = temp.First().Cast<Hyperlink>();
}
var workSheet = workSheetPart.Worksheet;
var cells = workSheet.Descendants<Cell>();
//loop each cell, find bookmark
foreach (var c in cells)
{
if (hyperLinks != null && hyperLinks.Count() > 0)
{
var hyperLink = hyperLinks.SingleOrDefault(x => x.Reference.Value == c.CellReference.Value);
if (hyperLink != null)
{
if (!string.IsNullOrEmpty(hyperLink.Location))
{
Console.WriteLine("Bookmark.DisplayName : " + hyperLink.Display);
Console.WriteLine("Bookmark.Location : " + hyperLink.Location);
//update bookmark
hyperLink.Location = "BookMark_Test";
hyperLink.Display = "updated bookmark";
Console.WriteLine("Bookmark.DisplayName after updated : " + hyperLink.Display);
Console.WriteLine("Bookmark.Location after updated : " + hyperLink.Location);
}
//for normal hyperlinks
//var hr = workSheetPart.HyperlinkRelationships.SingleOrDefault(x => x.Id == hyperLink.Id);
//if (hr != null)
//{
// Console.WriteLine(hr.Uri.ToString());
//}
}
}
workSheet.Save();
}
workbookPart.Workbook.Save();
}
}
}
Console.ReadKey();
}
}
}