A
A
Anton2013-08-23 14:51:55
Microsoft
Anton, 2013-08-23 14:51:55

Document template in docx/xlsx + data in xml using .NET tools, is it possible and if so, how?

Good day ... I would like to know about the possibility of performing the following task: You
need to create a document template in word / excel and then substitute data from XML (or another data source available in .NET) into this template using .NET tools. At the same time, the template should be easily edited in ms office without crutches like unpacking a .docx file and creating an xslt transformation from it.
All I could find on this topic was adding XML to the document and mapping XML tags to content controls, but I didn’t find collection mapping in any example, and I couldn’t do it myself - I achieved the maximum mapping of one collection element. Further, it seems like you can replace the attached XML with another using the OpenXML SDK, but first I would like to figure out the mapping.
I would appreciate any information on this matter.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
noonesshadow, 2013-08-23
@noonesshadow

Paid components easily. We use Syncfusion XlsIO for this.

E
exaller, 2014-05-05
@exaller

Did a similar task in PHP, but the principle is the same.
Take a .docx template, open it as a zip class object.
Then in this archive you read the required xml, and then str_replase.
Sample code:

//Папки Шаблона и загрузки нового файла
$template = 'templates/auditor';
$uploaddir = "documents/".$id;


//Файлы Шаблона и новый файл
$fileTemplate = $template .'/template.docx';
$newfile = $uploaddir .'/auditor_'. $num.'.docx';

//Создаём новую папку
if( !is_dir($uploaddir) ) mkdir( $uploaddir, 0755, true );

//Копируем файл
copy($fileTemplate, $newfile);

$zip = new ZipArchive;

if ($zip->open($newfile) === TRUE) {
  $handle = fopen( $template ."/document.xml", "r");
  $content = fread($handle, filesize($template ."/document.xml"));
  fclose($handle);
  $content = str_replace("{customer_r}", $auditor, $content);
  $content = str_replace("{num}", $data['Statement']['num'], $content);

  $zip->deleteName('word/document.xml');
  $zip->addFromString('word/document.xml',$content);
  $zip->close();
}else{
  echo "error";
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question