コード例 #1
0
        private void btnToWord_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Office.Interop.Word.Application winword =
                    new Microsoft.Office.Interop.Word.Application();

                winword.Visible = false;

                //Заголовок документа
                winword.Documents.Application.Caption = "CrimesAndIncidents";

                object missing = System.Reflection.Missing.Value;

                //Создание нового документа
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                //Добавление текста в документ
                document.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
                document.Content.SetRange(0, 0);

                //Добавление текста со стилем Заголовок 1
                Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
                //para1.Range.set_Style(styleHeading1);
                para1.Range.Font.Size = 14;
                para1.Range.Text      = "Преступления и происшествия за " +
                                        ((dpLeft.Text == "" && dpRight.Text == "") ? "все время" :
                                         ("период " +
                                          (dpLeft.Text == "" ? "" : "c " + dpLeft.Text) +
                                          (dpRight.Text == "" ? "" : " по " + dpRight.Text)));
                para1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                para1.Range.InsertParagraphAfter();
                para1.Range.InsertParagraphAfter();

                //Создание таблицы 5х5
                Microsoft.Office.Interop.Word.Table firstTable = document.Tables.Add(
                    para1.Range,
                    crimesDataGrid.Items.Count + 1, //число строк
                    crimesDataGrid.Columns.Count,   //число столбцов нужно динамически, после того как будет выбор столбцов
                    ref missing,
                    ref missing);

                firstTable.Range.Font.Size = 12;
                firstTable.Range.Font.Name = "Times New Roman";
                firstTable.Borders.Enable  = 1;

                for (int i = 0; i < firstTable.Rows.Count; i++)
                {
                    for (int j = 0; j < firstTable.Columns.Count; j++)
                    {
                        //Заголовок таблицы
                        if (i == 0)
                        {
                            firstTable.Rows[1].Cells[j + 1].Range.Text = j == 0 ? "№\nп/п" : crimesDataGrid.Columns[j].Header.ToString();

                            //Выравнивание текста в заголовках столбцов по центру
                            firstTable.Rows[i + 1].Cells[j + 1].VerticalAlignment =
                                Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            firstTable.Rows[i + 1].Cells[j + 1].Range.ParagraphFormat.Alignment =
                                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        }
                        //Значения ячеек
                        else if (j == 0)
                        {
                            firstTable.Rows[i + 1].Cells[j + 1].Range.Text = i.ToString();
                        }
                    }

                    if (i != 0)
                    {
                        firstTable.Rows[i + 1].Cells[2].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).NumberCase;
                        firstTable.Rows[i + 1].Cells[3].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).Story;
                        firstTable.Rows[i + 1].Cells[4].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).DateCommit;
                        firstTable.Rows[i + 1].Cells[5].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).DateInstitution;
                        firstTable.Rows[i + 1].Cells[6].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).DateRegistration;
                        firstTable.Rows[i + 1].Cells[7].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).Damage;
                        firstTable.Rows[i + 1].Cells[8].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).PostAccomplice;
                        firstTable.Rows[i + 1].Cells[9].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).Accomplice;
                        firstTable.Rows[i + 1].Cells[10].Range.Text = (crimesDataGrid.Items[i - 1] as Crime).Clause;
                        firstTable.Rows[i + 1].Cells[11].Range.Text = (crimesDataGrid.Items[i - 1] as Crime).DateVerdict;
                        firstTable.Rows[i + 1].Cells[12].Range.Text = (crimesDataGrid.Items[i - 1] as Crime).Verdict;
                        firstTable.Rows[i + 1].Cells[13].Range.Text = (crimesDataGrid.Items[i - 1] as Crime).MilitaryUnit;
                    }
                }
                firstTable.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent);

                winword.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #2
0
        /// <summary>
        /// Writes data contained in ADO.NET DataTable object to path stored in DocumentFilePath property.
        /// </summary>
        /// <param name="dt">DataTable object containing data to be imported.</param>
        /// <returns>True if output operation is successful. False if write fails.</returns>
        public bool WriteDataToDocument(DataTable dt)
        {
            bool   success = true;
            object missing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Application wordApp = null;
            Microsoft.Office.Interop.Word.Document    wordDoc = null;
            int numCols   = 0;
            int numRows   = 0;
            int tblRows   = 0;
            int curTblRow = 0;

            try
            {
                if (File.Exists(this.DocumentFilePath))
                {
                    if (_replaceExistingFile)
                    {
                        File.SetAttributes(this.DocumentFilePath, FileAttributes.Normal);
                        File.Delete(this.DocumentFilePath);
                    }
                    else
                    {
                        _msg.Length = 0;
                        _msg.Append("Word document file exists and ReplaceExistingFile set to False. Write to Word document has failed.");
                        throw new System.Exception(_msg.ToString());
                    }
                }

                numCols = dt.Columns.Count;
                numRows = dt.Rows.Count;
                tblRows = numRows + 1;

                wordApp         = new Microsoft.Office.Interop.Word.Application();
                wordApp.Visible = false;

                Microsoft.Office.Interop.Word.WdSaveFormat fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                switch (this.WordOutputFormat)
                {
                case enWordOutputFormat.Word2007:
                    fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument;
                    break;

                case enWordOutputFormat.Word2003:
                    fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                    break;

                case enWordOutputFormat.RTF:
                    fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF;
                    break;

                case enWordOutputFormat.PDF:
                    fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
                    break;

                default:
                    fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                    break;
                }

                wordDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                wordDoc.Content.SetRange(0, 0);
                Microsoft.Office.Interop.Word.Paragraph para1 = wordDoc.Content.Paragraphs.Add(ref missing);
                Microsoft.Office.Interop.Word.Table     tbl   = wordDoc.Tables.Add(para1.Range, tblRows, numCols, ref missing, ref missing);

                curTblRow = 1;
                for (int c = 0; c < dt.Columns.Count; c++)
                {
                    tbl.Rows[curTblRow].Cells[c + 1].Range.Text = dt.Columns[c].ColumnName;
                }

                for (int r = 0; r < dt.Rows.Count; r++)
                {
                    curTblRow++;
                    for (int c = 0; c < dt.Columns.Count; c++)
                    {
                        tbl.Rows[curTblRow].Cells[c + 1].Range.Text = dt.Rows[r][c].ToString();
                    }
                }


                tbl.AllowAutoFit = true;
                tbl.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitWindow);
                wordDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
                wordDoc.PageSetup.PaperSize   = Microsoft.Office.Interop.Word.WdPaperSize.wdPaper11x17;

                wordDoc.SaveAs2(this.DocumentFilePath, fileFormat, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                //wordDoc.Save();
                //wordDoc.Close(false);
                //wordApp.Quit(false);
                //((Microsoft.Office.Interop.Word._Document)wordDoc).Close(ref nullobject, ref nullobject, ref nullobject);
                //((Microsoft.Office.Interop.Word._Application)wordApp).Quit(ref nullobject, ref nullobject, ref nullobject);
                ((Microsoft.Office.Interop.Word._Document)wordDoc).Close(null, null, null);
                ((Microsoft.Office.Interop.Word._Application)wordApp).Quit(null, null, null);
            }
            catch (System.Exception ex)
            {
                success     = false;
                _msg.Length = 0;
                _msg.Append("Attempt to import DataTable into Word document failed.");
                _msg.Append(Environment.NewLine);
                _msg.Append(PFTextProcessor.FormatErrorMessage(ex));
                throw new System.Exception(_msg.ToString());
            }
            finally
            {
                if (wordApp != null)
                {
                    wordApp = null;
                }
            }

            return(success);
        }