OpenXML sdk 修改我的 Excel 文档中的工作表

发布于 2024-10-17 10:29:48 字数 4169 浏览 4 评论 0原文

我在 Excel 中创建了一个空模板。 我想打开模板并编辑文档,但我不知道如何更改现有工作表。 这就是代码:


using (SpreadsheetDocument xl = SpreadsheetDocument.Open(filename, true)) 
{ 
WorkbookPart wbp = xl.WorkbookPart; 
WorkbookPart workbook = xl.WorkbookPart; 
// Get the worksheet with the required name. 
// To be used to match the ID for the required sheet data 
// because the Sheet class and the SheetData class aren't 
// linked to each other directly. 
Sheet s = null; 
if (wbp.Workbook.Sheets.Elements().Count(nm => nm.Name == sheetName) == 0) 
{ 
// no such sheet with that name 
xl.Close(); 
return; 
} 
else 
{ 
s = (Sheet)wbp.Workbook.Sheets.Elements().Where(nm => nm.Name == sheetName).First(); 
} 

WorksheetPart wsp = (WorksheetPart)xl.WorkbookPart.GetPartById(s.Id.Value); 工作表 工作表 = new Worksheet(); SheetData sd = new SheetData(); //SheetData sd = (SheetData)wsp.Worksheet.GetFirstChild(); 样式表 styleSheet = workbook.WorkbookStylesPart.Stylesheet; //SheetDatasheetData = new SheetData(); //构建格式化的标题样式 UInt32Value headerFontIndex = util.CreateFont( 样式表, “阿里尔”, 10、 真的, 系统.绘图.颜色.红色);

//构建格式化日期样式 UInt32值日期字体索引= util.CreateFont( 样式表, “阿里尔”, 8、 真的, 系统.绘图.颜色.黑色);

//设置背景颜色样式 UInt32Value headerFillIndex = util.CreateFill( 样式表, 系统.绘图.颜色.黑色);

//通过组合字体/背景创建单元格样式 UInt32Value headerStyleIndex = util.CreateCellFormat( 样式表, 标题字体索引, 标题填充索引, 无效的); /* * 为特定格式创建一组基本单元格样式... * 如果您正在控制您的表格,那么您可以简单地创建您需要的样式, * 这组代码仍然是通用的。 */ _numberStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(3)); _doubleStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(4)); _dateStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(14)); _textStyleId = util.CreateCellFormat(styleSheet, headerFontIndex, headerFillIndex, null); _percentageStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(9));

util.AddNumber(xl,sheetName,(UInt32)3,“E”,“27”,_numberStyleId); util.AddNumber(xl,sheetName,(UInt32)3,“F”,“3.6”,_doubleStyleId); util.AddNumber(xl,sheetName,(UInt32)5,“L”,“5”,_percentageStyleId); util.AddText(xl,sheetName,(UInt32)5,“M”,“达里奥”,_textStyleId); util.AddDate(xl,sheetName,(UInt32)3,“J”,DateTime.Now,_dateStyleId); util.AddImage(xl, SheetName, imagePath, "微笑", "微笑", 30, 30); util.MergeCells(xl,sheetName,“D12”,“F12”); //util.DeleteValueCell(电子表格,sheetName,“F”,(UInt32)8);

txtCellText.Text = util.GetCellValue(xl,sheetName,(UInt32)5,“M”);

双数= util.GetCellDoubleValue(xl,sheetName,(UInt32)3,“E”); double numberD = util.GetCellDoubleValue(xl,sheetName,(UInt32)3,“F”); DateTime datee = util.GetCellDateTimeValue(xl,sheetName,(UInt32)3,“J”);

//txtDoubleCell.Text = util.GetCellValue(spreadsheet,sheetName,(UInt32)3,"P"); txtPercentualeCell.Text = util.GetCellValue(xl,sheetName,(UInt32)5,“L”);

字符串日期= util.GetCellValue(xl,sheetName,(UInt32)3,“J”); 双 dateD = Convert.ToDouble(日期); DateTime dateTime = DateTime.FromOADate(dateD); txtDateCell.Text = dateTime.ToShortDateString();

//工作表.Append(sd); /* 列列=新列(); columns.Append(util.CreateColumnData(10, 10, 40));

工作表.Append(列); */ SheetProtectionsheetProtection1 = new SheetProtection() { Sheet = true, Objects = true, Scenarios = true, SelectLockedCells = true, SelectUnlockedCells = true }; 工作表.Append(sheetProtection1); wsp.Worksheet = 工作表; wsp.Worksheet.Save();

xl.WorkbookPart.Workbook.Save(); xl.Close();

thanks!

更新

我尝试了一下,但不起作用。我正在使用此方法(GetWorksheetPart() ),但我想获取现有工作表,对其进行编辑并保存修改后的新文档。


using (SpreadsheetDocument xl = SpreadsheetDocument.Open(filename, true))
{
     WorkbookPart wbp = xl.WorkbookPart;

WorksheetPart worksheetPart = util.GetWorksheetPart(wbp, sheetName); SheetProtection sheetProtection1 = new SheetProtection() { Sheet = true, Objects = true, Scenarios = true, SelectLockedCells = true, SelectUnlockedCells = true }; worksheetPart.Worksheet.Append(sheetProtection1); worksheetPart.Worksheet.Save(); </pre></code>

我构建了文档但已损坏。为什么?

I create an empty template in excel.
I would like to open the template and edit the document but I do not know how to change the existing sheet.
That's the code:


using (SpreadsheetDocument xl = SpreadsheetDocument.Open(filename, true)) 
{ 
WorkbookPart wbp = xl.WorkbookPart; 
WorkbookPart workbook = xl.WorkbookPart; 
// Get the worksheet with the required name. 
// To be used to match the ID for the required sheet data 
// because the Sheet class and the SheetData class aren't 
// linked to each other directly. 
Sheet s = null; 
if (wbp.Workbook.Sheets.Elements().Count(nm => nm.Name == sheetName) == 0) 
{ 
// no such sheet with that name 
xl.Close(); 
return; 
} 
else 
{ 
s = (Sheet)wbp.Workbook.Sheets.Elements().Where(nm => nm.Name == sheetName).First(); 
} 

WorksheetPart wsp = (WorksheetPart)xl.WorkbookPart.GetPartById(s.Id.Value); Worksheet worksheet = new Worksheet(); SheetData sd = new SheetData(); //SheetData sd = (SheetData)wsp.Worksheet.GetFirstChild(); Stylesheet styleSheet = workbook.WorkbookStylesPart.Stylesheet; //SheetData sheetData = new SheetData(); //build the formatted header style UInt32Value headerFontIndex = util.CreateFont( styleSheet, "Arial", 10, true, System.Drawing.Color.Red);

//build the formatted date style UInt32Value dateFontIndex = util.CreateFont( styleSheet, "Arial", 8, true, System.Drawing.Color.Black);

//set the background color style UInt32Value headerFillIndex = util.CreateFill( styleSheet, System.Drawing.Color.Black);

//create the cell style by combining font/background UInt32Value headerStyleIndex = util.CreateCellFormat( styleSheet, headerFontIndex, headerFillIndex, null); /* * Create a set of basic cell styles for specific formats... * If you are controlling your table then you can simply create the styles you need, * this set of code is still intended to be generic. */ _numberStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(3)); _doubleStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(4)); _dateStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(14)); _textStyleId = util.CreateCellFormat(styleSheet, headerFontIndex, headerFillIndex, null); _percentageStyleId = util.CreateCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(9));

util.AddNumber(xl, sheetName, (UInt32)3, "E", "27", _numberStyleId); util.AddNumber(xl, sheetName, (UInt32)3, "F", "3.6", _doubleStyleId); util.AddNumber(xl, sheetName, (UInt32)5, "L", "5", _percentageStyleId); util.AddText(xl, sheetName, (UInt32)5, "M", "Dario", _textStyleId); util.AddDate(xl, sheetName, (UInt32)3, "J", DateTime.Now, _dateStyleId); util.AddImage(xl, sheetName, imagePath, "Smile", "Smile", 30, 30); util.MergeCells(xl, sheetName, "D12", "F12"); //util.DeleteValueCell(spreadsheet, sheetName, "F", (UInt32)8);

txtCellText.Text = util.GetCellValue(xl, sheetName, (UInt32)5, "M");

double number = util.GetCellDoubleValue(xl, sheetName, (UInt32)3, "E"); double numberD = util.GetCellDoubleValue(xl, sheetName, (UInt32)3, "F"); DateTime datee = util.GetCellDateTimeValue(xl, sheetName, (UInt32)3, "J");

//txtDoubleCell.Text = util.GetCellValue(spreadsheet, sheetName, (UInt32)3, "P"); txtPercentualeCell.Text = util.GetCellValue(xl, sheetName, (UInt32)5, "L");

string date = util.GetCellValue(xl, sheetName, (UInt32)3, "J"); double dateD = Convert.ToDouble(date); DateTime dateTime = DateTime.FromOADate(dateD); txtDateCell.Text = dateTime.ToShortDateString();

//worksheet.Append(sd); /* Columns columns = new Columns(); columns.Append(util.CreateColumnData(10, 10, 40));

worksheet.Append(columns); */ SheetProtection sheetProtection1 = new SheetProtection() { Sheet = true, Objects = true, Scenarios = true, SelectLockedCells = true, SelectUnlockedCells = true }; worksheet.Append(sheetProtection1); wsp.Worksheet = worksheet; wsp.Worksheet.Save();

xl.WorkbookPart.Workbook.Save(); xl.Close();


thanks!

Update

I try it but it doesn't work.I'm using yet this method (GetWorksheetPart() ) but i want to get the existing worksheet, edit it and save the new document modified.


using (SpreadsheetDocument xl = SpreadsheetDocument.Open(filename, true))
{
     WorkbookPart wbp = xl.WorkbookPart;

WorksheetPart worksheetPart = util.GetWorksheetPart(wbp, sheetName); SheetProtection sheetProtection1 = new SheetProtection() { Sheet = true, Objects = true, Scenarios = true, SelectLockedCells = true, SelectUnlockedCells = true }; worksheetPart.Worksheet.Append(sheetProtection1); worksheetPart.Worksheet.Save(); </pre></code>

I build the document BUT is corrupt. why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嘦怹 2024-10-24 10:29:48

要获取要编辑的现有工作表,请使用此代码来获取零件:

        public static WorksheetPart GetWorksheetPart(WorkbookPart workbookPart, string sheetName)
        {
            string relId = workbookPart.Workbook.Descendants<Sheet>()
                                 .Where(s => sheetName.Equals(s.Name))
                                 .First()
                                 .Id;

            return (WorksheetPart)workbookPart.GetPartById(relId);
        }

只需确保您正在搜索的工作表名称存在,否则您将遇到一些异常。然后使用对该 worksheetpart 的引用来执行您想要的任何编辑,最后只需调用 worksheetPart.Worksheet.Save();

EDIT

SheetProtection 元素需要插入到 SheetData 元素之后。附加时尝试此行:worksheetPart.Worksheet.Descendants().First().InsertAfterSelf(sheetProtection1);

To get an existing worksheet to edit use this code to get the part:

        public static WorksheetPart GetWorksheetPart(WorkbookPart workbookPart, string sheetName)
        {
            string relId = workbookPart.Workbook.Descendants<Sheet>()
                                 .Where(s => sheetName.Equals(s.Name))
                                 .First()
                                 .Id;

            return (WorksheetPart)workbookPart.GetPartById(relId);
        }

Just make sure that the sheetname exists you are searching for or you will get some exceptions. Then use the reference to that worksheetpart to perform any edits your want and at the end just call worksheetPart.Worksheet.Save();

EDIT

The SheetProtection element needs to be inserted after the SheetData element. Try this line when appending: worksheetPart.Worksheet.Descendants<SheetData>().First().InsertAfterSelf(sheetProtection1);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文