コード例 #1
0
        public void Generate(object sender, DoWorkEventArgs args)
        {
            WordReader wordReader = null;
            WordWriter wordWriter = null;
            int progressCount = 0;
            var worker = sender as BackgroundWorker;
            try
            {
                worker.ReportProgress(GetPercentage(progressCount++, MaxDataPoints), "生成プロセスを開始しています…");
                foreach (ExcelToWordMapping.MappingFileRow mappingFileRow in _mappingData.MappingFile)
                {
                    worker.ReportProgress(GetPercentage(progressCount++, MaxDataPoints), String.Format("ワードファイル「{0}」をテンプレートに生成しています…", mappingFileRow.WordTemplateFilePath));

                    #region 一つのファイルに書き出す下準備

                    if (WriteOutToOneFile)
                    {
                        if (mappingFileRow.IsWriteOutFilePathNull())
                        {
                            throw new Exception("WriteOutFilePathが設定されていません");
                        }

                        if (!Directory.Exists(Path.GetDirectoryName(mappingFileRow.WriteOutFilePath)))
                        {
                            throw new Exception(String.Format("ディレクトリ「{0}」が存在しません。",
                                Path.GetDirectoryName(mappingFileRow.WriteOutFilePath)));
                        }

                        if (WriteOutToOneFile && OverwriteExistingFiles)
                        {
                            if (File.Exists(mappingFileRow.WriteOutFilePath))
                            {
                                File.Delete(mappingFileRow.WriteOutFilePath);
                            }
                        }

                        File.Copy(mappingFileRow.WordTemplateFilePath, mappingFileRow.WriteOutFilePath);
                        File.SetAttributes(mappingFileRow.WriteOutFilePath,
                            File.GetAttributes(mappingFileRow.WriteOutFilePath) &
                            ~FileAttributes.ReadOnly);

                        wordReader = new WordReader(mappingFileRow.WriteOutFilePath);
                        wordReader.LoadFile();

                        if (!String.IsNullOrEmpty(ProtectPassword))
                        {
                            wordWriter = new WordWriter(wordReader);
                            wordWriter.UnprotectDocument(ProtectPassword);
                        }
                    } // if (WriteOutToOneFile)
                    else
                    {
                        OutputDirPath = mappingFileRow.OutputDirPath;

                        if (String.IsNullOrEmpty(OutputDirPath))
                        {
                            throw new Exception("OutputDirPathのプロパティをセットしてください。");
                        }

                        if (!Directory.Exists(OutputDirPath))
                        {
                            throw new IOException(String.Format("ディレクトリ{0}は存在しません。", OutputDirPath));
                        }
                    }

                    #endregion

                    if (!mappingFileRow.DoIt)
                        continue;

                    DataRow[] refSheetRows = mappingFileRow.GetChildRows("MappingHistory_RefSheet");
                    var generatedFiles = new Dictionary<string, string>();
                    var generatedPages = new Dictionary<string, Range>();

                    foreach (ExcelToWordMapping.RefSheetRow refSheetRow in refSheetRows)
                    {
                        worker.ReportProgress(GetPercentage(progressCount++, MaxDataPoints), String.Format("シート「{0}」を参照して氏名を抽出しています…", refSheetRow.RefSheetName));

                        if (StartingRow < refSheetRow.DataStartingRow)
                        {
                            StartingRow = refSheetRow.DataStartingRow;
                        }

                        Dictionary<int, string> identifiers = _excelReader.GetIdNames(refSheetRow.RefSheetName, StartingRow, EndingRow);
                        Dictionary<string, int> dataIdColumnList = _excelReader.GetColumnIdList(refSheetRow.ColumnIdRow, refSheetRow.RefSheetName);

                        int count = 1;
                        foreach (var identifier in identifiers)
                        {
                            worker.ReportProgress(GetPercentage(progressCount++, MaxDataPoints), String.Format("「{0}」に対してワードファイルを生成中…", refSheetRow.RefSheetName));
                            if (WriteOutToOneFile)
                            {
                                #region 一つのファイルに書き出すプロセス

                                if (wordReader == null)
                                {
                                    wordReader = new WordReader(mappingFileRow.WriteOutFilePath);
                                    wordReader.LoadFile();
                                }

                                if (wordWriter == null)
                                {
                                    wordWriter = new WordWriter(wordReader);
                                }

                                Range targetPage;
                                if (!generatedPages.ContainsKey(identifier.Value))
                                {
                                    targetPage = wordWriter.DuplicateFirstPage();
                                    generatedPages.Add(identifier.Value, targetPage);
                                }
                                else
                                {
                                    targetPage = generatedPages[identifier.Value];
                                }

                                // ここから実際にマッピングのデータを利用してエクセルからワードにデータを入力する。
                                Dictionary<int, Pair> identifierValues = _excelReader.GetValues(refSheetRow.RefSheetName, dataIdColumnList.Values.ToList(), identifier.Value);
                                foreach (ExcelToWordMapping.MappingRow mappingRow in refSheetRow.GetMappingRows())
                                {
                                    ContentControl targetContentControl = GetContentControl(targetPage.ContentControls, mappingRow.WordContentControlTitle);
                                    if (targetContentControl == null)
                                    {
                                        continue;
                                    }

                                    object value = null;
                                    string text = String.Empty;
                                    if (dataIdColumnList.ContainsKey(mappingRow.ExcelColumnIdName))
                                    {
                                        value = identifierValues[dataIdColumnList[mappingRow.ExcelColumnIdName]].Value;
                                        text = ConvertToZenkaku
                                            ? Strings.StrConv(
                                                identifierValues[dataIdColumnList[mappingRow.ExcelColumnIdName]]
                                                    .Text, VbStrConv.Wide, 1041)
                                            : identifierValues[dataIdColumnList[mappingRow.ExcelColumnIdName]].Text;
                                    }

                                    worker.ReportProgress(GetPercentage(progressCount++, MaxDataPoints), String.Format("{0}の{1}に値「{2}」を書き入れます。", mappingFileRow.WriteOutFilePath, mappingRow.WordContentControlTitle, text));
                                    SetContentControlValue(targetContentControl, text);
                                    if ((!mappingRow.IsScriptNull()) && !String.IsNullOrEmpty(mappingRow.Script))
                                    {
                                        try
                                        {
                                            var scriptExecuter = new WordScriptExecuter("C#", mappingRow.Script, _namespaces);
                                            scriptExecuter.ContentControl = targetContentControl;
                                            scriptExecuter.ActualValue = value;
                                            scriptExecuter.ExecuteScript();
                                        }
                                        catch (Exception scriptExp)
                                        {
                                            string errMsg = String.Format("{0}のスクリプトでエラーが発生しました。\r\n{1}", mappingRow.WordContentControlTitle, scriptExp.Message);
                                            throw new Exception(errMsg, scriptExp);
                                        }
                                    }
                                } // foreach (ExcelToWordMapping.MappingRow mappingRow in refSheetRow.GetMappingRows())

                                // ここから固定値の挿入へ。
                                DataRow[] literalValueMappingRows = _mappingData.Mapping.Select("LiteralValue IS NOT NULL");
                                if (literalValueMappingRows.Length > 0)
                                {
                                    foreach (ExcelToWordMapping.MappingRow literalValueMappingRow in literalValueMappingRows)
                                    {
                                        ContentControl targetContentControl = GetContentControl(targetPage.ContentControls, literalValueMappingRow.WordContentControlTitle);
                                        if (targetContentControl == null)
                                        {
                                            continue;
                                        }

                                        string text = literalValueMappingRow.LiteralValue;
                                        worker.ReportProgress(GetPercentage(progressCount++, MaxDataPoints), String.Format("{0}の{1}に値「{2}」を書き入れます。", mappingFileRow.WriteOutFilePath, literalValueMappingRow.WordContentControlTitle, text));
                                        SetContentControlValue(targetContentControl, text);
                                        if ((!literalValueMappingRow.IsScriptNull()) &&
                                            !String.IsNullOrEmpty(literalValueMappingRow.Script))
                                        {
                                            try
                                            {
                                                var scriptExecuter = new WordScriptExecuter("C#", literalValueMappingRow.Script, _namespaces);
                                                scriptExecuter.ContentControl = targetContentControl;
                                                scriptExecuter.ActualValue = text;
                                                scriptExecuter.ExecuteScript();
                                            }
                                            catch (Exception scriptExp)
                                            {
                                                string errMsg = String.Format("{0}のスクリプトでエラーが発生しました。\r\n{1}", literalValueMappingRow.WordContentControlTitle, scriptExp.Message);
                                                throw new Exception(errMsg, scriptExp);
                                            }
                                        }
                                    }
                                }

                                #endregion
                            }
                            else // if (WriteOutToOneFile)
                            {
                                #region 生成のターゲットになるワードファイルを決める。

                                string targetWordFile = String.Empty;
                                if (generatedFiles.ContainsKey(identifier.Value))
                                {
                                    targetWordFile = generatedFiles[identifier.Value];
                                }
                                else
                                {
                                    string fileName = Core.IO.Path.CleanFileName(identifier.Value);
                                    if (ConvertToZenkaku)
                                    {
                                        fileName = Strings.StrConv(fileName, VbStrConv.Wide, 1041);
                                    }

                                    if (AssignSequentialNumber)
                                    {
                                        string renban = count.ToString(CultureInfo.InvariantCulture).Length == 1
                                            ? "0" + count.ToString(CultureInfo.InvariantCulture)
                                            : count.ToString(CultureInfo.InvariantCulture);

                                        targetWordFile = Path.Combine(mappingFileRow.OutputDirPath, renban + ". " + fileName + Path.GetExtension(mappingFileRow.WordTemplateFilePath));
                                    }
                                    else if (AssignRowIndexNumber)
                                    {
                                        targetWordFile = Path.Combine(mappingFileRow.OutputDirPath, identifier.Key + ". " + fileName + Path.GetExtension(mappingFileRow.WordTemplateFilePath));
                                    }
                                    else
                                    {
                                        targetWordFile = Path.Combine(mappingFileRow.OutputDirPath,
                                            fileName +
                                            Path.GetExtension(
                                                mappingFileRow.WordTemplateFilePath));
                                    }

                                    if (File.Exists(targetWordFile) && (OverwriteExistingFiles))
                                    {
                                        File.Delete(targetWordFile);
                                    }

                                    File.Copy(mappingFileRow.WordTemplateFilePath, targetWordFile);
                                    File.SetAttributes(targetWordFile,
                                        File.GetAttributes(targetWordFile) & ~FileAttributes.ReadOnly);
                                    generatedFiles.Add(identifier.Value, targetWordFile);

                                    count++;
                                }

                                #endregion

                                #region 別々のファイルに書き出すプロセス

                                try
                                {
                                    //ここまででターゲットのワードファイルが決まったので、読み込んで値を入れていく。
                                    wordReader = new WordReader(targetWordFile);
                                    wordReader.LoadFile();

                                    // ここから実際にマッピングのデータを利用してエクセルからワードにデータを入力する。
                                    Dictionary<int, Pair> identifierValues = _excelReader.GetValues(refSheetRow.RefSheetName,
                                        dataIdColumnList.Values.ToList(), identifier.Value);

                                    foreach (ExcelToWordMapping.MappingRow mappingRow in refSheetRow.GetMappingRows())
                                    {
                                        ContentControl targetContentControl =
                                            wordReader.GetContentControl(mappingRow.WordContentControlTitle);
                                        if (targetContentControl == null)
                                        {
                                            continue;
                                        }

                                        object value = null;
                                        string text = String.Empty;
                                        if (dataIdColumnList.ContainsKey(mappingRow.ExcelColumnIdName))
                                        {
                                            value =
                                                identifierValues[dataIdColumnList[mappingRow.ExcelColumnIdName]].Value;
                                            text = ConvertToZenkaku
                                                ? Strings.StrConv(
                                                    identifierValues[dataIdColumnList[mappingRow.ExcelColumnIdName]]
                                                        .Text, VbStrConv.Wide, 1041)
                                                : identifierValues[dataIdColumnList[mappingRow.ExcelColumnIdName]].Text;
                                        }

                                        worker.ReportProgress(GetPercentage(progressCount++, MaxDataPoints),
                                            String.Format("{0}の{1}に値「{2}」を書き入れます。", targetWordFile,
                                                mappingRow.WordContentControlTitle, text));
                                        SetContentControlValue(targetContentControl, text);

                                        if ((!mappingRow.IsScriptNull()) && !String.IsNullOrEmpty(mappingRow.Script))
                                        {
                                            try
                                            {
                                                var scriptExecuter = new WordScriptExecuter("C#", mappingRow.Script, _namespaces);
                                                scriptExecuter.ContentControl = targetContentControl;
                                                scriptExecuter.ActualValue = value;
                                                scriptExecuter.ExecuteScript();
                                            }
                                            catch (Exception scriptExp)
                                            {
                                                string errMsg = String.Format("{0}のスクリプトでエラーが発生しました。\r\n{1}", mappingRow.WordContentControlTitle, scriptExp.Message);
                                                throw new Exception(errMsg, scriptExp);
                                            }
                                        }
                                    }
                                    // foreach (ExcelToWordMapping.MappingRow mappingRow in refSheetRow.GetMappingRows())

                                    // ここから固定値の挿入へ。
                                    DataRow[] literalValueMappingRows = _mappingData.Mapping.Select("LiteralValue IS NOT NULL");
                                    if (literalValueMappingRows.Length > 0)
                                    {
                                        foreach (
                                            ExcelToWordMapping.MappingRow literalValueMappingRow in literalValueMappingRows)
                                        {
                                            ContentControl targetContentControl = wordReader.GetContentControl(literalValueMappingRow.WordContentControlTitle);
                                            if (targetContentControl == null)
                                            {
                                                continue;
                                            }

                                            string text = literalValueMappingRow.LiteralValue;
                                            worker.ReportProgress(GetPercentage(progressCount++, MaxDataPoints), String.Format("{0}の{1}に値「{2}」を書き入れます。", targetWordFile, literalValueMappingRow.WordContentControlTitle, text));
                                            SetContentControlValue(targetContentControl, text);
                                        }
                                    }

                                    var writer = new WordWriter(wordReader);
                                    writer.SaveFilePath = targetWordFile;
                                    writer.Save();
                                    if (CancelRequested)
                                    {
                                        args.Cancel = true;
                                        return;
                                    }
                                }
                                finally
                                {
                                    if (wordReader != null)
                                        wordReader.Dispose();
                                }

                                #endregion
                            }
                        }
                    }

                    if (WriteOutToOneFile)
                    {
                        if (wordWriter != null)
                        {
                            wordWriter.SaveFilePath = mappingFileRow.WriteOutFilePath;
                            wordWriter.Save();
                        }

                        if (wordReader != null)
                            wordReader.Dispose();

                        if (CancelRequested)
                        {
                            args.Cancel = true;
                            worker.ReportProgress(100, "生成プロセスがキャンセルされました。");
                        }
                    }
                }

                var res = new {Text = "生成プロセスが終了しました。", Result = true};
                args.Result = res;
                //worker.ReportProgress(100, "生成プロセスが終了しました。");
                //args.Result = true;
            }
            catch (Exception exp)
            {
                var res = new {Text = exp.ToString(), Result = false};
                args.Result = res;
            }
            finally
            {
                if (wordReader != null)
                    wordReader.Dispose();
            }
        }