Exemplo n.º 1
0
        //</Snippet6>

        static void VS2008()
        {
            var wordApp = new Word.Application();

            wordApp.Visible = true;
            // docs is a collection of all the Document objects currently
            // open in Word.
            Word.Documents docs = wordApp.Documents;

            // Add a document to the collection and name it doc.
            object useDefaultVal = Type.Missing;

            Word.Document doc = docs.Add(ref useDefaultVal, ref useDefaultVal,
                                         ref useDefaultVal, ref useDefaultVal);

            object n = 0;

            Word.Range range = doc.Range(ref n, ref n);

            range.InsertAfter("Testing, testing, testing. . .");

            //<Snippet14>
            // Call to ConvertToTable in Visual C# 2008 or earlier. This code
            // is not part of the solution.
            var    missing   = Type.Missing;
            object separator = ",";

            range.ConvertToTable(ref separator, 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);
            //</Snippet14>
        }
Exemplo n.º 2
0
        static void DisplayInWord()
        {
            var wordApp = new Word.Application();

            wordApp.Visible = true;
            // docs is a collection of all the Document objects currently
            // open in Word.
            Word.Documents docs = wordApp.Documents;

            // Add a document to the collection and name it doc.
            Word.Document doc = docs.Add();

            //<Snippet7>
            // Define a range, a contiguous area in the document, by specifying
            // a starting and ending character position. Currently, the document
            // is empty.
            Word.Range range = doc.Range(0, 0);

            // Use the InsertAfter method to insert a string at the end of the
            // current range.
            range.InsertAfter("Testing, testing, testing. . .");
            //</Snippet7>

            // You can comment out any or all of the following statements to
            // see the effect of each one in the Word document.

            // Next, use the ConvertToTable method to put the text into a table.
            // The method has 16 optional parameters. You only have to specify
            // values for those you want to change.

            //<Snippet9>
            // Convert to a simple table. The table will have a single row with
            // three columns.
            range.ConvertToTable(Separator: ",");
            //</Snippet9>

            // Change to a single column with three rows..
            //<Snippet10>
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1);
            //</Snippet10>

            // Format the table.
            //<Snippet11>
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1,
                                 Format: Word.WdTableFormat.wdTableFormatElegant);
            //</Snippet11>
        }
Exemplo n.º 3
0
        private static void Main(string[] args)
        {
            //создаём документ
            Word.Application word = new Word.Application();
            object           miss = Missing.Value;
            //object path = @"C:\Users\Андрей\Documents\Visual Studio 2015\Projects\Studing.git\Word_Lab_5_KPP\Doc.docx";
            object readOnly = false;

            //object isVisible = false;
            word.Visible = false;
            // Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss,
            //    ref miss, ref miss, ref miss, ref miss, ref miss, ref isVisible, ref miss, ref miss, ref miss, ref miss);
            Console.WriteLine("Запуск построения таблиц в файле");

            string[,] text = new string[, ]
            {
                { "Привлеченные средства коммерческого банка", "Сумма, млн. грн." },
                { "Депозиты государственных предприятий", "2000" },
                { "Депозиты с/х предприятий", "850" },
                { "Депозиты СП", "700" },
                { "Вклады населения", "4000" },
                { "Депозиты внебюджетных фондов", "1000" },
                { "Депозиты АО и ТОО", "1200" },
                { "Остатки на расчетных и текущих счетах клиентов", "8000" },
                { "Депозиты юридических лиц в валюте (в грн.)", "5000" }
            };
            int rows    = text.GetLength(0); //количество строк
            int columns = text.GetLength(1); //количество столбцов

            word.Visible = true;
            object oEndOfDoc = "\\endofdoc";

            Word.Document docs = word.Documents.Add(ref miss, ref miss, ref miss, ref miss);

            #region 1-й вариант путем непосредственного использования коллекции Tables объекта Document.

            string msg = "1-й вариант путем непосредственного использования коллекции Tables объекта Document";
            InsertParagraph(docs, msg); //вставляем параграф перед текстом

            var selection = word.Selection;
            //Range означает захват промежутка данных между объектами документа (текста, параграфа, таблицы и т.д.)
            Word.Range range = selection.Range;
            Word.Table table;
            Word.Range wrdRng = docs.Bookmarks.get_Item(ref oEndOfDoc).Range; //вставляем таблицу после параграфа то есть в конце документа
            table = docs.Tables.Add(wrdRng, rows, columns, ref miss, ref miss);
            for (int i = 1; i <= rows; i++)
            {
                for (int j = 1; j <= columns; j++)
                {
                    table.Cell(i, j).Range.Text = text[i - 1, j - 1];
                }
            }
            SetFormatTable(table, rows, columns);

            #endregion

            #region 2-й вариант путем преобразования текста в таблицу с помощью метода ConvertToTable объекта Range

            msg = "2-й вариант путем преобразования текста в таблицу с помощью метода ConvertToTable объекта Range";
            InsertParagraph(docs, msg);

            range = docs.Bookmarks.get_Item(ref oEndOfDoc).Range;  //вставляем таблицу после параграфа то есть в конце документа
            string outText;
            for (int i = 0; i < rows; i++)
            {
                outText = "";
                for (int j = 0; j < columns; j++)
                {
                    outText += text[i, j] + "|";
                }
                //добавляем наш текст сначала встроку ячейки будут разбиваться по "|"
                range.InsertAfter(outText);
                range.InsertParagraphAfter();
            }
            //конвертируем содержимое (строки) в таблицу по "|"
            range.ConvertToTable("|");
            //форматируем внешний вид таблицы
            Word.Table tbl = docs.Tables[2];
            SetFormatTable(tbl, rows, columns);

            #endregion

            CloseDocument(/*path, */ word, docs, miss, readOnly);
            Console.ReadKey();
        }
Exemplo n.º 4
0
        /// <summary>
        /// 將 DataTable 插入至指定的 Word Range 位置
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="oRange"></param>
        /// <returns></returns>
        public static Word.Table CreateWordTableWithDataTable(DataTable dt, Word.Range oRange)
        {
            int RowCount    = dt.Rows.Count;
            int ColumnCount = dt.Columns.Count;

            Object[,] DataArray = new object[RowCount, ColumnCount];
            //int RowCount = 0; int ColumnCount = 0;
            int r = 0;

            for (int c = 0; c <= ColumnCount - 1; c++)
            {
                DataColumn dc = dt.Columns[c];
                object[]   colValues;
                #region    的資料型態轉換格式化
                if (dc.DataType == typeof(double))
                {
                    var o = dt.AsEnumerable().Select(x => Math.Round(x.Field <double>(dc.ColumnName), 4)).ToArray();
                    colValues = new object[o.Length];
                    o.CopyTo(colValues, 0);
                }
                else if (dc.DataType == typeof(DateTime))
                {
                    var o = dt.AsEnumerable().Select(x => string.Format("{0:yyyy-MM-dd hh:mm:ss}", x.Field <DateTime>(dc.ColumnName))).ToArray();
                    colValues = new object[o.Length];
                    o.CopyTo(colValues, 0);
                }
                else
                {
                    var o = dt.AsEnumerable().Select(x => x[dc.ColumnName]).ToArray();
                    colValues = new object[o.Length];
                    o.CopyTo(colValues, 0);
                }
                #endregion
                for (r = 0; r <= RowCount - 1; r++)
                {
                    DataArray[r, c] = colValues[r];
                } //end row loop
            }     //end column loop

            StringBuilder oTemp = new StringBuilder();
            for (r = 0; r <= RowCount - 1; r++)
            {
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    oTemp.Append(DataArray[r, c] + "\t");
                }
            }

            oRange.Text = oTemp.ToString();
            object     Separator       = Word.WdTableFieldSeparator.wdSeparateByTabs;
            object     Format          = Word.WdTableFormat.wdTableFormatWeb1;
            object     ApplyBorders    = true;
            object     AutoFit         = true;
            object     AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;
            Word.Table tbl             = oRange.ConvertToTable(Separator: Separator,
                                                               NumRows: RowCount,
                                                               NumColumns: ColumnCount,
                                                               ApplyBorders: ApplyBorders, AutoFit: AutoFit, AutoFitBehavior: AutoFitBehavior);
            tbl.Rows.AllowBreakAcrossPages = 0;
            tbl.Rows.Alignment             = Word.WdRowAlignment.wdAlignRowCenter;
            tbl.Rows.Add(tbl.Rows[1]);
            //gotta do the header row manually
            for (int c = 0; c <= ColumnCount - 1; c++)
            {
                tbl.Cell(1, c + 1).Range.Text = dt.Columns[c].ColumnName;
            }
            tbl.set_Style(Word.WdBuiltinStyle.wdStyleTableLightGrid);
            return(tbl);
        }