Created
August 19, 2014 11:39
-
-
Save AuthorProxy/6539ee5f9431292e5596 to your computer and use it in GitHub Desktop.
OpenXML SDK Sample: Find and replace marks with text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using DocumentFormat.OpenXml.Packaging; | |
| using DocumentFormat.OpenXml.Spreadsheet; | |
| namespace OpenXML_ReadAndReplaceMarks | |
| { | |
| class Program | |
| { | |
| private static readonly char markSymbol = '$'; | |
| private static readonly string filePath = @"d:\test.xlsx"; | |
| static void Main( string[] args) | |
| { | |
| using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filePath, true )) | |
| { | |
| WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; | |
| WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); | |
| SharedStringTablePart stringTablePart = workbookPart.SharedStringTablePart; | |
| SharedStringTable stringTable = stringTablePart.SharedStringTable; | |
| IEnumerable<SharedStringItem> values = stringTable.Elements<SharedStringItem>(); | |
| foreach ( var entry in values) | |
| { | |
| if (entry.Text.Text.First() != markSymbol | |
| || entry.Text.Text.Last() != markSymbol | |
| || String.IsNullOrEmpty(entry.Text.Text)) | |
| continue; | |
| switch (entry.Text.Text.ToUpper()) | |
| { | |
| // Имя абонента: | |
| case "$NAME$": | |
| entry.Text.Text = "Иван"; | |
| continue; | |
| // Фамилия абонента: | |
| case "$SURNAME$": | |
| entry.Text.Text = "Грозный" ; | |
| continue; | |
| // Мобильный телефон: | |
| case "$PHONE$": | |
| entry.Text.Text = "03"; | |
| continue; | |
| // Электронная почта: | |
| case "$MAIL$": | |
| entry.Text.Text = "царь@всеяруси.рф" ; | |
| continue; | |
| // Город регистрации: | |
| case "$REGISTRATION$": | |
| entry.Text.Text = "Кремль" ; | |
| continue; | |
| default: | |
| throw new NotImplementedException("Unrecognized text mark: " + entry.Text.Text + Environment.NewLine + "Should be implemented in switch case!"); | |
| } | |
| } | |
| workbookPart.Workbook.Save(); | |
| spreadsheetDocument.Close(); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment