Skip to content

Instantly share code, notes, and snippets.

@cpereira7
Last active November 4, 2017 19:45
Show Gist options
  • Select an option

  • Save cpereira7/a1dcd6615b398c5d6dd67a50ed97fee4 to your computer and use it in GitHub Desktop.

Select an option

Save cpereira7/a1dcd6615b398c5d6dd67a50ed97fee4 to your computer and use it in GitHub Desktop.
Permite criar vários documentos Word a partir de um template e substituição de campos por dados de um ficheiro CSV
using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Linq;
using Novacode;
namespace Csv2Doc
{
class Program
{
public static void Main(string[] args)
{
var versao = Assembly.GetEntryAssembly().GetName().Version;
Console.Title = "CSV to Docx v." + versao ;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("----------------------");
Console.WriteLine(" CSV to Docx ");
Console.WriteLine("----------------------");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Versão: " + versao);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("\nInstruções: ");
Console.WriteLine(" - Carregar um ficheiro CSV e Word (docx) com nomes iguais. \n\tPor exemplo: " +
"cartas.csv e cartas.docx");
Console.WriteLine("\n - O ficheiro Docx deve conter os campos a substituir no formato \"[campo]\" e " +
"o ficheiro CSV deve conter nome igual no seu cabeçalho para cada campo" +
"\n\tExemplo coluna \"nome\" > [nome] no template");
CreateFolders();
int menuchoice = 0;
while (menuchoice != 7)
{
Console.WriteLine("\nMenu:");
Console.WriteLine(" 1. Abrir Pasta de Trabalho (adicionar template e .csv)");
Console.WriteLine(" 2. Gerar documentos");
Console.WriteLine(" 3. Abrir Pasta de Destino");
Console.WriteLine(" 7. Sair");
Console.Write("\nIntroduza a sua opção: ");
try
{
menuchoice = int.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Formato incorreto");
}
switch (menuchoice)
{
case 1:
Process.Start(ReturnFolders(true));
break;
case 2:
var fileName = DadosInput();
ConvertFiles(ReturnFolders(true) +fileName);
break;
case 3:
Process.Start(ReturnFolders(false));
break;
case 7:
break;
default:
Console.WriteLine("Opção não existe.");
break;
}
}
Console.Write("\nPress any key to continue . . . ");
Console.ReadKey(true);
}
private static void CreateFolders()
{
var folder = AppDomain.CurrentDomain.BaseDirectory;
System.IO.Directory.CreateDirectory(folder + @"\Dados");
System.IO.Directory.CreateDirectory(folder + @"\Export");
}
/// <summary>
/// Retorna path para uma das pastas
/// </summary>
/// <param name="input">True se pasta de input.</param>
private static string ReturnFolders(bool input)
{
var folder = AppDomain.CurrentDomain.BaseDirectory;
if (input)
return folder + @"\Dados\";
return folder + @"\Export\";
}
private static string DadosInput()
{
ConsoleKeyInfo key;
string document = "";
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("\nIntroduza o nome do conjunto de ficheiros: ");
Console.ForegroundColor = ConsoleColor.White;
do
{
key = Console.ReadKey(true);
// Backspace Should Not Work
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
document += key.KeyChar;
Console.Write(key.KeyChar);
}
else
{
if (key.Key == ConsoleKey.Backspace && document.Length > 0)
{
document = document.Substring(0, (document.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
return document;
}
private static void ConvertFiles(string dataName)
{
var csvFile = dataName+".csv";
var docFile = dataName+".docx";
//Check files
if (!File.Exists(dataName+".docx") && !File.Exists(csvFile))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n\nERRO. Conjunto de Ficheiros Inválido.");
Console.WriteLine("Verifique se ambos os ficheiro têm o mesmo nome e formato válido (.csv | .docx)");
Console.ForegroundColor = ConsoleColor.White;
return;
}
else
Console.WriteLine("\n\nFicheiros Encontrados. A processar...");
var csvData = ReadCsv(csvFile);
if (csvData.Count > 1)
ProcessFiles(csvData, docFile);
}
private static List<string[]> ReadCsv(string fileName)
{
//Default encoding Win1252
var fileLines = File.ReadAllLines(fileName, System.Text.Encoding.GetEncoding(1252)).ToList();
var csv = from line in fileLines select (line.Split(';')).ToArray();
return csv.ToList();
}
private static void ProcessFiles(List<string[]> csvData, string template)
{
Console.WriteLine("Headers a substituir no template: ");
Console.WriteLine(string.Join(" | ", csvData[0]));
Console.WriteLine("------------------------------------------------");
for (int i = 1; i < csvData.Count; i++) {
var element = csvData[i];
Console.WriteLine(string.Join(" | ", element));
var name = ReturnFolders(false) + string.Format("{0}_{1}.docx", DateTime.Now.Millisecond, element[0]);
using (DocX docx = DocX.Load(template))
{
for (int j = 0; j < element.Length; j++) {
docx.ReplaceText(string.Format("[{0}]", csvData[0][j].ToLower()), element[j]);
}
docx.SaveAs(name);
}
ExportPDF(name);
}
}
private static void ExportPDF(string filename)
{
var wordApp = new Microsoft.Office.Interop.Word.Application();
var wordDocument = wordApp.Documents.Open(filename);
wordDocument.Save();
wordDocument.ExportAsFixedFormat(filename.Replace("docx", "pdf"), Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
wordDocument.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges,
Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat,
false);
wordApp.Quit();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment