我正在使用Open XML创建Excel。我想将背景图像添加到Excel。 不要告诉我添加图像到excel并与OpenXML生产力工具进行比较。 请让我知道提取方法吗?
答案 0 :(得分:0)
我已经深入研究了使用 OpenXML 将背景图像应用于 Excel 并且我正在共享代码。
class Program
{
static void Main(string[] args)
{
//pathe of the Excel file to add background image
string document = @"Book1.xlsx";
// Open the document for editing.
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(document, true))
{
// Get existing sheets from workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>();
// Loop through all sheets and add image as background
foreach (var sheet in sheets.Elements<Sheet>())
{
WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id);
CreateWorksheetPart(worksheetPart);
}
}
}
public static void CreateWorksheetPart(WorksheetPart part)
{
ImagePart imagePart1 = part.ImageParts.FirstOrDefault();
if (imagePart1 == null)
imagePart1 = part.AddNewPart<ImagePart>("image/jpeg", "rId1");
string str = part.GetIdOfPart(imagePart1);
GenerateImagePart1Content(imagePart1);
GeneratePartContent(part, str);
}
private static void GenerateImagePart1Content(ImagePart imagePart1)
{
using (var stream = new FileStream("WatermarkDoc.png", FileMode.Open))
{
imagePart1.FeedData(stream);
}
}
private static void GeneratePartContent(WorksheetPart part, string idPart)
{
Worksheet worksheet1 = part.Worksheet;
Picture picture1 = new Picture() { Id = idPart };
worksheet1.Append(picture1);
}
}
使用以下工具查找 openXML 中的更多类。 https://www.microsoft.com/en-us/download/details.aspx?id=30425?