Ejemplo n.º 1
0
 // 给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值
 public void InsertCell(int n, int row, int columns, string[] values)
 {
     Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
     for (int i = 0; i < columns; i++)
     {
         table.Cell(row, i + 1).Range.Text = values[i];
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Ghi dữ liệu vào bảng
 /// </summary>
 /// <param name="indexTable">Bảng dữ liệu được tính bắt đầu từ 1 trở đi.</param>
 /// <param name="rows">Dòng dữ liệu được tính từ 1</param>
 /// <param name="columns">Cột dữ liệu được tính từ 1</param>
 /// <param name="values">Chuỗi dữ liệu cần ghi</param>
 public void WriteDataTables(int indexTable, int rows, int columns, string values)
 {
     try
     {
         Microsoft.Office.Interop.Word.Table dt = doc.Tables[indexTable];
         dt.Cell(rows, columns).Range.Text = values;
     }
     catch
     { }
 }
Ejemplo n.º 3
0
        // 给表格插入rows行,n为表格的序号
        public void AddRow(int n, int rows)
        {
            object miss = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
            for (int i = 0; i < rows; i++)
            {
                table.Rows.Add(ref miss);
            }
        }
Ejemplo n.º 4
0
        public void WriteTable(int rowIndex, int colIndex, int tableIndex)
        {
            table = doc.Tables[tableIndex];
            string text = table.Cell(rowIndex, colIndex).Range.Text.ToString();

            text = text.Substring(0, text.Length - 2);
            Console.WriteLine(text);
            Console.WriteLine(doc.Tables.Count.ToString());
            Console.WriteLine(1);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Thêm một dòng vào bảng tại vị trí cuối.
 /// </summary>
 /// <param name="indexTable">Bảng dữ liệu được tính bắt đầu từ 1 trở đi.</param>
 public void InsertRowsInTables(int indexTable)
 {
     try
     {
         Microsoft.Office.Interop.Word.Table dt = doc.Tables[indexTable];
         object beforeRow = Type.Missing;
         dt.Rows.Add(ref beforeRow);
     }
     catch
     { }
 }
Ejemplo n.º 6
0
 public void DeleteRowsTable(int indexTable, int beforeRows)
 {
     try
     {
         Microsoft.Office.Interop.Word.Table dt = doc.Tables[indexTable];
         Word.Range Ranges = dt.Range;
         Ranges.Rows[beforeRows].Delete();
     }
     catch
     { }
 }
Ejemplo n.º 7
0
 /// <summary>
 /// 设置表格字体
 /// </summary>
 /// <param name="table">表格对象</param>
 /// <param name="fontName">字体名称</param>
 /// <param name="size">字体大小</param>
 public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size)
 {
     if (size != 0)
     {
         table.Range.Font.Size = Convert.ToSingle(size);
     }
     if (fontName != "")
     {
         table.Range.Font.Name = fontName;
     }
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Thêm một dòng vào bảng tại vị trí xác định
 /// </summary>
 /// <param name="indexTable">Bảng dữ liệu được tính bắt đầu từ 1 trở đi.</param>
 /// <param name="beforeRow">Dòng được tính bắc đầu từ 1</param>
 public void InsertRowsInTables(int indexTable, int beforeRow)
 {
     try
     {
         Microsoft.Office.Interop.Word.Table dt = doc.Tables[indexTable];
         Word.Range Range      = dt.Range;
         object     beforeRows = Range.Rows[beforeRow];
         dt.Rows.Add(ref beforeRows);
     }
     catch
     { }
 }
        /// <summary>
        /// 导出Word 的方法
        /// </summary>
        private void tslExport_Word()
        {
            SaveFileDialog sfile = new SaveFileDialog();

            sfile.AddExtension = true;
            sfile.DefaultExt   = ".doc";
            sfile.Filter       = "(*.doc)|*.doc";
            sfile.FileName     = "理文检测系统质检数据统计Word报表" + DateTime.Now.ToShortDateString();
            if (sfile.ShowDialog() == DialogResult.OK)
            {
                object path = sfile.FileName;
                Object none = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Application wordApp  = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
                //建立表格
                Microsoft.Office.Interop.Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, dgvCarStatisticsQC.Rows.Count + 1, dgvCarStatisticsQC.Columns.Count, ref none, ref none);
                try
                {
                    for (int i = 0; i < dgvCarStatisticsQC.Columns.Count; i++)//设置标题
                    {
                        table.Cell(0, i + 1).Range.Text = dgvCarStatisticsQC.Columns[i].HeaderText;
                    }
                    for (int i = 1; i < dgvCarStatisticsQC.Rows.Count; i++)//填充数据
                    {
                        for (int j = 0; j < dgvCarStatisticsQC.Columns.Count; j++)
                        {
                            //table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                            if (dgvCarStatisticsQC[j, i - 1].Value != null)
                            {
                                table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                            }
                        }
                    }
                    document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
                    document.Close(ref none, ref none, ref none);
                    MessageBox.Show("导出数据成功!");
                }

                finally
                {
                    wordApp.Quit(ref none, ref none, ref none);
                }
            }
        }
Ejemplo n.º 10
0
        //生成Word
        private static string createTempWord(string templateFilePath, Dictionary <string, string> dic, System.Data.DataTable dt)
        {
            WordHelper wordBuilder = new WordHelper();

            wordBuilder.CreateNewDocument(templateFilePath);
            foreach (var item in dic)
            {
                wordBuilder.InsertReplaceText(item.Key, item.Value);
            }
            Microsoft.Office.Interop.Word.Table table = wordBuilder.InsertTable("BOOKMARK_TABLE", dt.Rows.Count + 1, 12, 0);
            wordBuilder.SetParagraph_Table(table, 0, 0);
            wordBuilder.SetFont_Table(table, string.Empty, 10);
            wordBuilder.InsertCell(table, 1, 1, "序号");
            wordBuilder.InsertCell(table, 1, 2, "汽车生产企业");
            wordBuilder.InsertCell(table, 1, 3, "车辆型号");
            wordBuilder.InsertCell(table, 1, 4, "燃料种类");
            wordBuilder.InsertCell(table, 1, 5, "整车整备质量");
            wordBuilder.InsertCell(table, 1, 6, "变速器型式");
            wordBuilder.InsertCell(table, 1, 7, "座位排数");
            wordBuilder.InsertCell(table, 1, 8, "纯电动驱动模式综合工况续驶里程");
            wordBuilder.InsertCell(table, 1, 9, "车型燃料消耗量目标值①");
            wordBuilder.InsertCell(table, 1, 10, "综合工况燃烧消耗量实际值②");
            wordBuilder.InsertCell(table, 1, 11, "实际生产/进口量③");
            wordBuilder.InsertCell(table, 1, 12, "备注");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                table.Cell(i + 2, 1).Range.Text  = (i + 1).ToString();
                table.Cell(i + 2, 2).Range.Text  = dt.Rows[i]["Qcscqy"].ToString();
                table.Cell(i + 2, 3).Range.Text  = dt.Rows[i]["Clxh"].ToString();
                table.Cell(i + 2, 4).Range.Text  = dt.Rows[i]["Rllx"].ToString();
                table.Cell(i + 2, 5).Range.Text  = dt.Rows[i]["Zczbzl"].ToString();
                table.Cell(i + 2, 6).Range.Text  = dt.Rows[i]["Bsqxs"].ToString();
                table.Cell(i + 2, 7).Range.Text  = dt.Rows[i]["Zwps"].ToString();
                table.Cell(i + 2, 8).Range.Text  = dt.Rows[i]["Zhgkxslc"].ToString();
                table.Cell(i + 2, 9).Range.Text  = dt.Rows[i]["TgtZhgkrlxhl"].ToString();
                table.Cell(i + 2, 10).Range.Text = dt.Rows[i]["ActZhgkrlxhl"].ToString();
                table.Cell(i + 2, 11).Range.Text = dt.Rows[i]["Sl_act"].ToString();
            }
            string tempWordName = String.Format("{0}\\tempYear1.doc", DefaultDirectory.TempDoc);

            wordBuilder.SaveDocument(tempWordName);
            return(tempWordName);
        }
Ejemplo n.º 11
0
        //生成Word
        private static void createWord(string TemplatePath, string imagePath, Dictionary <string, string> dic, string SavePath, System.Data.DataTable dt)
        {
            WordHelper wordBuilder = new WordHelper();

            wordBuilder.CreateNewDocument(TemplatePath);
            foreach (var item in dic)
            {
                wordBuilder.InsertReplaceText(item.Key, item.Value);
            }
            if (!string.IsNullOrEmpty(imagePath))
            {
                wordBuilder.InsertPicture("BOOKMARK_SIGNATURE", imagePath, 100, 100);
            }
            Microsoft.Office.Interop.Word.Table table = wordBuilder.InsertTable("BOOKMARK_TABLE", dt.Rows.Count + 1, 10, 0);
            wordBuilder.SetParagraph_Table(table, 0, 0);
            wordBuilder.SetFont_Table(table, string.Empty, 10, 0);
            table.Cell(1, 1).Range.Text  = "序号";
            table.Cell(1, 2).Range.Text  = "备案号(VIN)";
            table.Cell(1, 3).Range.Text  = "车辆型号";
            table.Cell(1, 4).Range.Text  = "通用名称";
            table.Cell(1, 5).Range.Text  = "燃料种类";
            table.Cell(1, 6).Range.Text  = "综合工况燃料消耗量";
            table.Cell(1, 7).Range.Text  = "整车整备质量";
            table.Cell(1, 8).Range.Text  = "变速器型式";
            table.Cell(1, 9).Range.Text  = "座位排数";
            table.Cell(1, 10).Range.Text = "操作类型";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                wordBuilder.InsertCell(table, i + 2, 1, (i + 1).ToString());
                for (int j = 2; j < 10; j++)
                {
                    wordBuilder.InsertCell(table, i + 2, j, dt.Rows[i][j - 1].ToString());
                }
                wordBuilder.InsertCell(table, i + 2, 10, dt.Rows[i][12].ToString());
            }
            wordBuilder.SaveDocument(SavePath);
        }
Ejemplo n.º 12
0
        private void btnCalculate_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(tbCalculate.Text) == 0)
            {
                MessageBox.Show("Невозможно выбить пустой чек", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            wordapp         = new Word.Application();
            wordapp.Visible = true;
            Word.Paragraph wordParagraph;
            Word.Document  doc          = new Word.Document();
            object         MyTemplate   = Type.Missing;
            object         NewTemplate  = false;
            object         DocumentType = Word.WdNewDocumentType.wdNewBlankDocument;
            object         Visible      = true;

            doc = wordapp.Documents.Add(ref MyTemplate, ref NewTemplate, ref DocumentType, ref Visible);

            object pargf = Type.Missing;

            wordParagraph = doc.Content.Paragraphs.Add(ref pargf);
            Microsoft.Office.Interop.Word.Table tbl1 = null;
            object DefaultTableBehavior = Word.WdDefaultTableBehavior.wdWord9TableBehavior;
            object AutoFitBehavior      = Word.WdAutoFitBehavior.wdAutoFitContent;

            string[] ListGas = new string[] { grpGas.Text, label2.Text, radCount.Text, radSum.Text };
            string[] List;
            if ((Convert.ToInt32(tbQuantityGas.Text) != 0) || (Convert.ToInt32(tbSumCostGas.Text) != 0))
            {
                if (radCount.Checked)
                {
                    List = new string[] { cmbGas.Text, tbCostGas.Text, tbQuantityGas.Text, tbPayGas.Text };
                }
                else
                {
                    List = new string[] { cmbGas.Text, tbCostGas.Text, tbPayGas.Text, tbSumCostGas.Text };
                }
                tbl1 = doc.Content.Tables.Add(wordParagraph.Range, ListGas.Count(), 2, ref DefaultTableBehavior, ref AutoFitBehavior);
                tbl1.Borders.Enable = 1;
                for (int i = 0; i < ListGas.Count(); i++)
                {
                    tbl1.Cell(i + 1, 1).Range.Text = ListGas[i];
                    tbl1.Cell(i + 1, 2).Range.Text = List[i];
                }
            }

            string[] ListMag = new string[4];
            string[] ListQuantityMag = new string[4];
            string[] ListCostMag = new string[4];
            int      count = 0, sum = 0;

            if ((Convert.ToInt32(tbQuantityHotDog.Text) != 0) && chkHotDog.Checked)
            {
                ListMag[count]        += chkHotDog.Text;
                ListQuantityMag[count] = tbQuantityHotDog.Text;
                ListCostMag[count]     = tbCostHotDog.Text;
                count++;
                sum += (Convert.ToInt32(tbQuantityHotDog.Text) * Convert.ToInt32(tbCostHotDog.Text));
            }
            if ((Convert.ToInt32(tbQuantityGamburger.Text) != 0) && chkGamburger.Checked)
            {
                ListMag[count]         = chkGamburger.Text;
                ListQuantityMag[count] = tbQuantityGamburger.Text;
                ListCostMag[count]     = tbCostGamburger.Text;
                count++;
                sum += (Convert.ToInt32(tbQuantityGamburger.Text) * Convert.ToInt32(tbCostGamburger.Text));
            }
            if ((Convert.ToInt32(tbQuantityChizburger.Text) != 0) && chkChizburger.Checked)
            {
                ListMag[count]         = chkChizburger.Text;
                ListQuantityMag[count] = tbQuantityChizburger.Text;
                ListCostMag[count]     = tbCostChizburger.Text;
                count++;
                sum += (Convert.ToInt32(tbQuantityChizburger.Text) * Convert.ToInt32(tbCostChizburger.Text));
            }
            if ((Convert.ToInt32(tbQuantityCocaCola.Text) != 0) && chkCocaCola.Checked)
            {
                ListMag[count]         = chkCocaCola.Text;
                ListQuantityMag[count] = tbQuantityCocaCola.Text;
                ListCostMag[count]     = tbCostCocaCola.Text;
                count++;
                sum += (Convert.ToInt32(tbQuantityCocaCola.Text) * Convert.ToInt32(tbCostCocaCola.Text));
            }
            if (count != 0)
            {
                if (tbl1 != null)
                {
                    wordParagraph.Range.Font.Size = 1;
                    wordParagraph.Range.InsertParagraphAfter();
                    wordParagraph.Range.Font.Size = 11;
                }
                tbl1 = doc.Content.Tables.Add(wordParagraph.Range, count + 1, 3, ref DefaultTableBehavior, ref AutoFitBehavior);
                tbl1.Borders.Enable = 1;
                for (int i = 0; i < count; i++)
                {
                    tbl1.Cell(i + 1, 1).Range.Text = ListMag[i];
                    tbl1.Cell(i + 1, 2).Range.Text = ListQuantityMag[i];
                    tbl1.Cell(i + 1, 3).Range.Text = ListCostMag[i];
                }
                tbl1.Cell(count + 1, 1).Range.Text = "Всего";
                tbl1.Cell(count + 1, 3).Range.Text = sum.ToString();
            }

            wordParagraph.Range.Bold = 2;
            wordParagraph.Range.Text = label12.Text + " " + tbCalculate.Text;
            allSum                  += Convert.ToDouble(tbCalculate.Text);
            tbQuantityGas.Text       = tbSumCostGas.Text = tbQuantityHotDog.Text = tbQuantityGamburger.Text = tbQuantityChizburger.Text = tbQuantityCocaCola.Text = "0";
            chkHotDog.Checked        = chkGamburger.Checked = chkChizburger.Checked = chkCocaCola.Checked = false;
            tbQuantityHotDog.Enabled = tbQuantityGamburger.Enabled = tbQuantityChizburger.Enabled = tbQuantityCocaCola.Enabled = false;
            radCount.Checked         = true;
        }
Ejemplo n.º 13
0
 /// <summary>
 /// 合并单元格
 /// </summary>
 /// <param name="table">表格对象</param>
 /// <param name="row1">开始行号</param>
 /// <param name="column1">开始列号</param>
 /// <param name="row2">结束行号</param>
 /// <param name="column2">结束列号</param>
 public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2)
 {
     table.Cell(row1, column1).Merge(table.Cell(row2, column2));
 }
Ejemplo n.º 14
0
        /// <summary>
        /// 插入表格
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="haveBorder">是否有边框</param>
        /// <param name="colWidths">边距</param>
        /// <param name="bookmark">标签</param>
        /// <param name="wd">自动调整方式</param>
        /// <returns></returns>
        public bool InsertTable(string bookmark, System.Data.DataTable dt, bool haveBorder, double[] colWidths, WdAutoFitBehavior wd)
        {
            try
            {
                object oBookmark     = bookmark;                                     //WORD中预定义的书签
                Range  tableLocation = oDoc.Bookmarks.get_Item(ref oBookmark).Range; //获取当前文档的书签位置。
                //oWord.Selection.GoTo(oBookmark);
                // Range tableLocation2 = oWord.Selection.Range;
                object Nothing = System.Reflection.Missing.Value;
                tableLocation.InsertParagraphAfter();//插入一个段落,在此段落上插入一个2行一列的表格。
                // Microsoft.Office.Interop.Word.Table newTable = oDoc.Tables.Add(tableLocation, 2, 1, ref Nothing, ref Nothing);
                //添加Word表格
                Microsoft.Office.Interop.Word.Table table = oDoc.Tables.Add(tableLocation, dt.Rows.Count, dt.Columns.Count, ref Nothing, ref Nothing);


                if (colWidths != null)
                {
                    for (int i = 0; i < colWidths.Length; i++)
                    {
                        table.Columns[i + 1].Width = (float)(28.5F * colWidths[i]);
                    }
                }


                ///设置TABLE的样式
                table.AllowAutoFit = true;
                table.AutoFitBehavior(wd);//设置自动调整方式
                table.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast;
                //table.Rows.Height = oWord.CentimetersToPoints(float.Parse("0.8"));
                table.Range.Font.Size = 9.0F;
                table.Range.Font.Name = "宋体";
                table.Range.Font.Bold = 0;
                table.Rows.Alignment  = WdRowAlignment.wdAlignRowCenter;
                table.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                table.Range.Cells.VerticalAlignment   = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                if (haveBorder == true)
                {
                    //设置外框样式
                    table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                    table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                    //样式设置结束
                }

                for (int row = 0; row < dt.Rows.Count; row++)
                {
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        table.Cell(row + 1, col + 1).Range.Text = dt.Rows[row][col].ToString();
                    }
                }


                return(true);
            }
            catch (Exception e)
            {
                //   MessageBox.Show(e.ToString(), "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
Ejemplo n.º 15
0
        private string InitRead(string Template, Dictionary <string, string> datas, System.Data.DataTable dt, string userType, string year, string qymc)
        {
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word.Document    doc = null;
            //将要导出的新word文件名
            string physicNewFile = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc";

            try
            {
                app         = new Microsoft.Office.Interop.Word.Application();             //创建word应用程序
                app.Visible = false;
                object fileName = System.Windows.Forms.Application.StartupPath + Template; //Year1;//模板文件
                //打开模板文件
                object oMissing = System.Reflection.Missing.Value;
                doc = app.Documents.Open(ref fileName,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);



                object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                foreach (var item in datas)
                {
                    app.Selection.Find.Replacement.ClearFormatting();
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Text             = item.Key;   //需要被替换的文本
                    app.Selection.Find.Replacement.Text = item.Value; //替换文本

                    //执行替换操作
                    app.Selection.Find.Execute(
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing, ref oMissing,
                        ref oMissing, ref replace,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing);
                }

                object unit;
                unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
                app.Selection.EndKey(ref unit, ref oMissing);
                app.Selection.TypeParagraph(); //插入段落

                if (userType == "C")           //国产
                {
                    app.Selection.Text = String.Format("{0}年{1}企业国产乘用车产品燃料消耗量", year.Substring(0, 4), qymc);
                    Word.Range range = doc.Paragraphs.Last.Range;
                    Microsoft.Office.Interop.Word.Table table = app.Selection.Tables.Add(range, dt.Rows.Count + 1, 12, ref oMissing, ref oMissing);
                    //设置表格的字体大小粗细
                    table.Range.Font.Size = 10;
                    table.Range.Font.Bold = 0;
                    //为表格划线
                    range.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle        = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle       = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle      = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle     = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle   = WdLineStyle.wdLineStyleSingle;

                    //设置表格标题
                    table.Cell(1, 1).Range.Text  = "序号";
                    table.Cell(1, 2).Range.Text  = "汽车生产企业";
                    table.Cell(1, 3).Range.Text  = "车辆型号";
                    table.Cell(1, 4).Range.Text  = "燃料种类";
                    table.Cell(1, 5).Range.Text  = "整车整备质量";
                    table.Cell(1, 6).Range.Text  = "变速器型式";
                    table.Cell(1, 7).Range.Text  = "座位排数";
                    table.Cell(1, 8).Range.Text  = "纯电动驱动模式综合工况续驶里程";
                    table.Cell(1, 9).Range.Text  = "车型燃料消耗量目标值①";
                    table.Cell(1, 10).Range.Text = "综合工况燃烧消耗量实际值②";
                    table.Cell(1, 11).Range.Text = "实际生产量③";
                    table.Cell(1, 12).Range.Text = "备注";

                    //循环数据创建数据行
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        table.Cell(i + 2, 1).Range.Text  = (i + 1).ToString();
                        table.Cell(i + 2, 2).Range.Text  = dt.Rows[i]["Qcscqy"].ToString();
                        table.Cell(i + 2, 3).Range.Text  = dt.Rows[i]["Clxh"].ToString();
                        table.Cell(i + 2, 4).Range.Text  = dt.Rows[i]["Rllx"].ToString();
                        table.Cell(i + 2, 5).Range.Text  = dt.Rows[i]["Zczbzl"].ToString();
                        table.Cell(i + 2, 6).Range.Text  = dt.Rows[i]["Bsqxs"].ToString();
                        table.Cell(i + 2, 7).Range.Text  = dt.Rows[i]["Zwps"].ToString();
                        table.Cell(i + 2, 8).Range.Text  = dt.Rows[i]["Zhgkxslc"].ToString();
                        table.Cell(i + 2, 9).Range.Text  = dt.Rows[i]["TgtZhgkrlxhl"].ToString();
                        table.Cell(i + 2, 10).Range.Text = dt.Rows[i]["ActZhgkrlxhl"].ToString();
                        table.Cell(i + 2, 11).Range.Text = dt.Rows[i]["Sl_act"].ToString();
                    }
                }
                else  //进口
                {
                    app.Selection.Text = String.Format("{0}年{1}企业进口乘用车产品燃料消耗量", year.Substring(0, 4), qymc);
                    Word.Range range = doc.Paragraphs.Last.Range;
                    Microsoft.Office.Interop.Word.Table table = app.Selection.Tables.Add(range, dt.Rows.Count + 1, 12, ref oMissing, ref oMissing);
                    //设置表格的字体大小粗细
                    table.Range.Font.Size = 10;
                    table.Range.Font.Bold = 0;
                    //为表格划线
                    range.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle        = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle       = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle      = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle     = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle   = WdLineStyle.wdLineStyleSingle;

                    //设置表格标题
                    table.Cell(1, 1).Range.Text  = "序号";
                    table.Cell(1, 2).Range.Text  = "汽车生产企业";
                    table.Cell(1, 3).Range.Text  = "车辆型号";
                    table.Cell(1, 4).Range.Text  = "燃料种类";
                    table.Cell(1, 5).Range.Text  = "整车整备质量";
                    table.Cell(1, 6).Range.Text  = "变速器型式";
                    table.Cell(1, 7).Range.Text  = "座位排数";
                    table.Cell(1, 8).Range.Text  = "纯电动驱动模式综合工况续驶里程";
                    table.Cell(1, 9).Range.Text  = "车型燃料消耗量目标值①";
                    table.Cell(1, 10).Range.Text = "综合工况燃烧消耗量实际值②";
                    table.Cell(1, 11).Range.Text = "实际生产量③";
                    table.Cell(1, 12).Range.Text = "备注";

                    //循环数据创建数据行
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        table.Cell(i + 2, 1).Range.Text  = (i + 1).ToString();
                        table.Cell(i + 2, 2).Range.Text  = dt.Rows[i]["Qcscqy"].ToString();
                        table.Cell(i + 2, 3).Range.Text  = dt.Rows[i]["Clxh"].ToString();
                        table.Cell(i + 2, 4).Range.Text  = dt.Rows[i]["Rllx"].ToString();
                        table.Cell(i + 2, 5).Range.Text  = dt.Rows[i]["Zczbzl"].ToString();
                        table.Cell(i + 2, 6).Range.Text  = dt.Rows[i]["Bsqxs"].ToString();
                        table.Cell(i + 2, 7).Range.Text  = dt.Rows[i]["Zwps"].ToString();
                        table.Cell(i + 2, 8).Range.Text  = dt.Rows[i]["Zhgkxslc"].ToString();
                        table.Cell(i + 2, 9).Range.Text  = dt.Rows[i]["TgtZhgkrlxhl"].ToString();
                        table.Cell(i + 2, 10).Range.Text = dt.Rows[i]["ActZhgkrlxhl"].ToString();
                        table.Cell(i + 2, 11).Range.Text = dt.Rows[i]["Sl_act"].ToString();
                    }
                }

                unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
                app.Selection.EndKey(ref unit, ref oMissing);
                app.Selection.TypeParagraph();//插入段落


                app.Selection.Text = @"注:①车型燃料消耗量目标值,同一车辆型号因整车整备质量、座位排数、变速器形式不同有多个不同的燃料消耗量目标值时,计算企业平均消耗量目标值时采用最小的燃料消耗量目标值。
②综合工况燃料消耗量实际值,四舍五入至小数点后一位;如汽车燃料消耗量通告系统中同一车型有多个不同的综合工况燃料消耗量实际值,则填写该车型最高的综合工况燃料消耗量实际值。
③实际生产量/实际进口量,不含出口量。";


                //对替换好的word模板另存为一个新的word文档
                doc.SaveAs(System.Windows.Forms.Application.StartupPath + "\\ExcelHeaderTemplate\\" + physicNewFile,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

                //准备导出word
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭word文档
                }
                if (app != null)
                {
                    app.Quit();//退出word应用程序
                }
            }
            return(physicNewFile);
        }
Ejemplo n.º 16
0
        public bool InsertTable(DataTable dt, bool haveBorder, double[] colWidths, string[] MergeAry)
        {
            try
            {
                object Nothing = System.Reflection.Missing.Value;
                int    lenght  = oDoc.Characters.Count - 1;
                object start   = lenght;
                object end     = lenght;
                //表格起始坐标
                Microsoft.Office.Interop.Word.Range tableLocation = oDoc.Range(ref start, ref end);
                //添加Word表格
                Microsoft.Office.Interop.Word.Table table =
                    oDoc.Tables.Add(tableLocation, dt.Rows.Count, dt.Columns.Count, ref Nothing, ref Nothing);
                if (colWidths != null)
                {
                    for (int i = 0; i < colWidths.Length; i++)
                    {
                        table.Columns[i + 1].Width = (float)(28.5F * colWidths[i]);
                    }
                }

                ///设置TABLE的样式
                table.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast;
                table.Rows.Height     = oWordApplic.CentimetersToPoints(float.Parse("0.8"));
                table.Range.Font.Size = 10.5F;
                table.Range.Font.Name = "宋体";
                table.Range.Font.Bold = 0;
                table.Range.ParagraphFormat.Alignment =
                    Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                table.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                if (haveBorder == true)
                {
                    //设置外框样式
                    table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                    table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                    //样式设置结束
                }
                for (int row = 0; row < dt.Rows.Count; row++)
                {
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        table.Cell(row + 1, col + 1).Range.Text = dt.Rows[row][col].ToString();
                    }
                }
                if (MergeAry != null)
                {
                    foreach (string mStr in MergeAry)
                    {
                        string[] cellStr = mStr.Split(',');
                        table.Cell(int.Parse(cellStr[0]), int.Parse(cellStr[1]))
                        .Merge(table.Cell(int.Parse(cellStr[2]), int.Parse(cellStr[3])));
                    }
                }
                ////table.Cell(dt.Rows.Count,2).Merge(table.Cell(dt.Rows.Count,dt.Columns.Count));

                ////table.Cell(dt.Rows.Count, 1).Merge(table.Cell(dt.Rows.Count, 3));

                return(true);
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.ToString(), "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            finally
            {
            }
        }
Ejemplo n.º 17
0
        private void printJournal()
        {
            this.Cursor = Cursors.WaitCursor;
            //Объект приложения word
            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    document    = null;
            //Путь к файлу
            object pathFile = "E:\\zhurnal.docx";
            object missing  = Type.Missing;
            Object falseObj = false;

            try
            {
                //Загружаем документ
                document = application.Documents.Add(ref pathFile, ref missing, ref missing, ref missing);


                //Очищаем параметры поиска
                // ???????
                application.Selection.Find.ClearFormatting();
                application.Selection.Find.Replacement.ClearFormatting();

                //Замена значений
                RPS("@куратор", Journal.Curator.ToString(), application, missing);
                RPS("@должность", Journal.Curator.positionCurator, application, missing);
                RPS("@группа", Journal.Group.numberGroup, application, missing);
                RPS("@курс", Journal.courceGroup.ToString(), application, missing);
                RPS("@шифр", Journal.Group.cipher.ToString(), application, missing);
                RPS("@учебный год", Journal.yearJournal.Year.ToString() + "/" + Journal.yearJournal.AddYears(1).Year, application, missing);
                RPS("@специальность", Journal.Group.specialtyGroup, application, missing);
                Microsoft.Office.Interop.Word.Table tableStatus    = application.ActiveDocument.Tables[5];
                Microsoft.Office.Interop.Word.Table tableStipendia = application.ActiveDocument.Tables[7];

                int jTableSt   = 1;
                int jTableStip = 2;
                foreach (JournalStudent journalStudent in DBobjects.Entities.JournalStudent.Where(p => p.idJournal == Journal.idJournal).ToList().OrderBy(p => p.Student.surnameStudent))
                {
                    if (journalStudent.StatusStudent.nameSatusSt != "Нет")
                    {
                        if (jTableSt > 1)
                        {
                            tableStatus.Rows.Add(ref missing);
                        }
                        tableStatus.Rows[jTableSt].Cells[1].Range.Text = jTableSt.ToString() + ".";
                        tableStatus.Rows[jTableSt].Cells[2].Range.Text = journalStudent.StatusStudent.nameSatusSt;
                        tableStatus.Rows[jTableSt].Cells[3].Range.Text = journalStudent.Student.ToString();
                        jTableSt++;
                    }
                    if (jTableStip > 2)
                    {
                        tableStipendia.Rows.Add(ref missing);
                    }
                    tableStipendia.Rows[jTableStip].Cells[2].Range.Text = journalStudent.Student.surnameStudent + " " + journalStudent.Student.nameStudent + " " + journalStudent.Student.patronymicStudent;
                    if (journalStudent.stipendSemOne == true)
                    {
                        tableStipendia.Rows[jTableStip].Cells[3].Range.Text = "+";
                    }
                    if (journalStudent.stipendSemTwo == true)
                    {
                        tableStipendia.Rows[jTableStip].Cells[4].Range.Text = "+";
                    }
                    jTableStip++;
                }
                Microsoft.Office.Interop.Word.Table tableInfSt = application.ActiveDocument.Tables[6];
                int jTableInfStud = 2;
                Microsoft.Office.Interop.Word.Table tableVladimir = application.ActiveDocument.Tables[8];
                int jTableVladimir = 2;
                Microsoft.Office.Interop.Word.Table tableInogor = application.ActiveDocument.Tables[9];
                int jTableInogor = 2;
                Microsoft.Office.Interop.Word.Table tablefamilyChild = application.ActiveDocument.Tables[10];
                int jTablefamilyChild = 2;
                Microsoft.Office.Interop.Word.Table tableFamily = application.ActiveDocument.Tables[11];
                int jTableFamily = 2;
                Microsoft.Office.Interop.Word.Table tableFamChild = application.ActiveDocument.Tables[12];
                int jTableFamChild = 2;
                Microsoft.Office.Interop.Word.Table tableLargeRelatives = application.ActiveDocument.Tables[13];
                int jLargeRelatives = 2;
                Microsoft.Office.Interop.Word.Table tableIncomplete = application.ActiveDocument.Tables[14];
                int jIncomplete = 2;
                Microsoft.Office.Interop.Word.Table tableInvaildParents = application.ActiveDocument.Tables[15];
                int jInvaildParents = 2;
                Microsoft.Office.Interop.Word.Table tableQuadian = application.ActiveDocument.Tables[16];
                int jQuadian = 2;
                Microsoft.Office.Interop.Word.Table tableInvaildStudent = application.ActiveDocument.Tables[17];
                int            jInvaildStudent = 2;
                List <Student> students        = DBobjects.Entities.Student.Where(p => p.idGroup == Journal.idGroup).ToList();

                students = students.OrderBy(p => p.surnameStudent).ToList();
                foreach (Student student in students)
                {
                    if (jTableInfStud > 2)
                    {
                        tableInfSt.Rows.Add(ref missing);
                    }
                    tableInfSt.Rows[jTableInfStud].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                    if (student.formOfTrainStudent == true)
                    {
                        tableInfSt.Rows[jTableInfStud].Cells[3].Range.Text = "К";
                    }
                    else
                    {
                        tableInfSt.Rows[jTableInfStud].Cells[3].Range.Text = "Б";
                    }
                    tableInfSt.Rows[jTableInfStud].Cells[4].Range.Text = student.dateOfBirthStudent.ToShortDateString();
                    tableInfSt.Rows[jTableInfStud].Cells[5].Range.Text = student.telephoneStudent;


                    if (student.Residence.town.Contains("Владимир") == true)
                    {
                        if (jTableVladimir > 2)
                        {
                            tableVladimir.Rows.Add(ref missing);
                        }
                        tableVladimir.Rows[jTableVladimir].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                        string adress = student.Residence.country + ", " + student.Residence.region + ", " + student.Residence.district + ", " + student.Residence.town + ", " + student.Residence.street + ", " + student.Residence.korpus + ", " + student.Residence.house + ", " + student.Residence.flat + " ";
                        adress = adress.Replace(", ,", ",");
                        adress = adress.Replace(", ,", ",");
                        adress = adress.TrimEnd(',', ' ');
                        tableVladimir.Rows[jTableVladimir].Cells[3].Range.Text = adress;
                        jTableVladimir++;
                    }
                    else
                    {
                        if (jTableInogor > 2)
                        {
                            tableInogor.Rows.Add(ref missing);
                        }
                        tableInogor.Rows[jTableInogor].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                        string adressPerman = student.Residence.country + ", " + student.Residence.region + ", " + student.Residence.district + ", " + student.Residence.town + ", " + student.Residence.street + ", " + student.Residence.korpus + ", " + student.Residence.house + ", " + student.Residence.flat + " ";
                        adressPerman = adressPerman.Replace(", ,", ",");
                        adressPerman = adressPerman.Replace(", ,", ",");
                        adressPerman = adressPerman.TrimEnd(',', ' ');
                        tableInogor.Rows[jTableInogor].Cells[3].Range.Text = adressPerman;

                        if (student.Residence1.idHostel == 0 || student.Residence1.idHostel == null)
                        {
                            string adressTemp = student.Residence1.country + ", " + student.Residence1.region + ", " + student.Residence1.district + ", " + student.Residence1.town + ", " + student.Residence1.street + ", " + student.Residence1.korpus + ", " + student.Residence1.house + ", " + student.Residence1.flat + " ";
                            adressTemp = adressTemp.Replace(", ,", ",");
                            adressTemp = adressTemp.Replace(", ,", ",");
                            adressTemp = adressPerman.TrimEnd(',', ' ');
                            tableInogor.Rows[jTableInogor].Cells[4].Range.Text = adressTemp;
                            jTableInogor++;
                        }
                        else
                        {
                            tableInogor.Rows[jTableInogor].Cells[4].Range.Text = student.Residence1.Hostel.adressHostel + ". Комната " + student.Residence1.room;

                            jTableInogor++;
                        }
                    }
                    if (student.Family.Count() != 0)
                    {
                        Family family = DBobjects.Entities.Family.FirstOrDefault(p => p.idStudent == student.idStudent);
                        if (String.IsNullOrEmpty(family.nameChild) == false)
                        {
                            if (jTablefamilyChild > 2)
                            {
                                tablefamilyChild.Rows.Add(ref missing);
                            }
                            tablefamilyChild.Rows[jTablefamilyChild].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                            tablefamilyChild.Rows[jTablefamilyChild].Cells[3].Range.Text = family.nameChild + "\n" + family.dateOfBirthChild.Value.ToShortDateString();
                            tablefamilyChild.Rows[jTablefamilyChild].Cells[4].Range.Text = family.fullNameSpous + "\n" + family.professionSpous;
                            jTablefamilyChild++;
                        }
                        if (String.IsNullOrEmpty(family.fullNameSpous) == false)
                        {
                            if (jTableFamily > 2)
                            {
                                tableFamily.Rows.Add(ref missing);
                            }
                            if (student.gender == true)
                            {
                                tableFamily.Rows[jTableFamily].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                                tableFamily.Rows[jTableFamily].Cells[3].Range.Text = family.fullNameSpous;
                            }
                            else
                            {
                                tableFamily.Rows[jTableFamily].Cells[3].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                                tableFamily.Rows[jTableFamily].Cells[2].Range.Text = family.fullNameSpous;
                            }
                            if (family.nameChild != null)
                            {
                                tableFamily.Rows[jTableFamily].Cells[4].Range.Text = family.nameChild.ToString() + "\n" + family.dateOfBirthChild.Value.ToShortDateString().ToString();
                            }
                            jTableFamily++;
                        }
                        if (String.IsNullOrEmpty(family.nameChild) == false && student.gender == true && String.IsNullOrEmpty(family.fullNameSpous) == true)
                        {
                            if (jTableFamChild > 2)
                            {
                                tableFamChild.Rows.Add(ref missing);
                            }
                            tableFamChild.Rows[jTableFamChild].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                            tableFamChild.Rows[jTableFamChild].Cells[3].Range.Text = family.nameChild + "\n" + family.dateOfBirthChild.Value.ToShortDateString();
                            jTableFamChild++;
                        }
                    }
                    List <Kin> kins = DBobjects.Entities.Kin.Where(p => p.idStudent == student.idStudent).ToList();

                    if (kins.Where(p => p.kinStatus == "Брат" || p.kinStatus == "Сестра").Count() >= 2)
                    {
                        if (jLargeRelatives > 2)
                        {
                            tableLargeRelatives.Rows.Add(ref missing);
                        }
                        tableLargeRelatives.Rows[jLargeRelatives].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                        tableLargeRelatives.Rows[jLargeRelatives].Cells[3].Range.Text = (kins.Where(p => p.kinStatus == "Брат" || p.kinStatus == "Сестра").Count() + 1).ToString();
                        jLargeRelatives++;
                    }
                    if (kins.Where(p => p.kinStatus == "Мать" || p.kinStatus == "Отец" && p.kinStatus != "Опекун").Count() < 2 && kins.Count() != 0)
                    {
                        if (jIncomplete > 2)
                        {
                            tableIncomplete.Rows.Add(ref missing);
                        }
                        tableIncomplete.Rows[jIncomplete].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                        foreach (Kin kin in kins)
                        {
                            if (kin.kinStatus == "Мать")
                            {
                                tableIncomplete.Rows[jIncomplete].Cells[3].Range.Text = kin.kinStatus + " " + kin.fullNameKin + "\nОтец -";
                            }
                            if (kin.kinStatus == "Отец")
                            {
                                tableIncomplete.Rows[jIncomplete].Cells[3].Range.Text = kin.kinStatus + " " + kin.fullNameKin + "\nМать -";
                            }
                        }
                        jIncomplete++;
                    }
                    foreach (Kin kin in kins)
                    {
                        if (kin.disabilityKin == true && kin.kinStatus != "Опекун" && kin.kinStatus != "Брат" && kin.kinStatus != "Сестра")
                        {
                            if (jInvaildParents > 2)
                            {
                                tableInvaildParents.Rows.Add(ref missing);
                            }
                            tableInvaildParents.Rows[jInvaildParents].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                            tableInvaildParents.Rows[jInvaildParents].Cells[3].Range.Text = kin.fullNameKin;
                            jInvaildParents++;
                        }

                        if (kin.kinStatus == "Опекун")
                        {
                            if (jQuadian > 2)
                            {
                                tableQuadian.Rows.Add(ref missing);
                            }
                            tableQuadian.Rows[jQuadian].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                            tableQuadian.Rows[jQuadian].Cells[3].Range.Text = kin.fullNameKin + "\n" + kin.telephoneKin;
                            jQuadian++;
                        }
                    }
                    if (student.disabilityStudent == true)
                    {
                        if (jInvaildStudent > 2)
                        {
                            tableInvaildStudent.Rows.Add(ref missing);
                        }
                        tableInvaildStudent.Rows[jInvaildStudent].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                        String rez = "";
                        foreach (Kin kin in kins)
                        {
                            if (kin.kinStatus == "Мать" || kin.kinStatus == "Отец" || kin.kinStatus == "Опекун")
                            {
                                rez += kin.kinStatus + " " + kin.fullNameKin + "\n";
                            }
                        }
                        rez = rez.TrimEnd('\n', ' ');
                        tableInvaildStudent.Rows[jInvaildStudent].Cells[3].Range.Text = rez;
                    }
                    jTableInfStud++;
                }
                Microsoft.Office.Interop.Word.Table tableDynamics = application.ActiveDocument.Tables[18];
                int jDynamics = 3;
                foreach (GroupDynamics groupDynamics in DBobjects.Entities.GroupDynamics.Where(p => p.idJournal == Journal.idJournal).ToList())
                {
                    if (jDynamics > 3)
                    {
                        tableDynamics.Rows.Add(ref missing);
                    }
                    tableDynamics.Cell(jDynamics, 2).Range.Text = groupDynamics.CoreIndicator.ToString();
                    tableDynamics.Cell(jDynamics, 3).Range.Text = Math.Round(groupDynamics.semesterOneDyn, 2).ToString();
                    tableDynamics.Cell(jDynamics, 4).Range.Text = Math.Round(Convert.ToDouble(groupDynamics.semesterTwoDyn), 2).ToString();
                    tableDynamics.Cell(jDynamics, 5).Range.Text = groupDynamics.note;
                    jDynamics++;
                }

                Microsoft.Office.Interop.Word.Table tableGrafik = application.ActiveDocument.Tables[19];
                int jGrafic = 4;
                foreach (StudyingProcess studyingProcess in DBobjects.Entities.StudyingProcess.Where(p => p.idJournal == Journal.idJournal).ToList())
                {
                    if (jGrafic > 4)
                    {
                        tableGrafik.Rows.Add(ref missing);
                    }
                    tableGrafik.Cell(jGrafic, 1).Range.Text = Journal.courceGroup.ToString();
                    tableGrafik.Cell(jGrafic, 2).Range.Text = studyingProcess.semester.ToString();
                    tableGrafik.Cell(jGrafic, 3).Range.Text = studyingProcess.semesterStart.ToShortDateString();
                    tableGrafik.Cell(jGrafic, 4).Range.Text = studyingProcess.semesterEnd.ToShortDateString();
                    tableGrafik.Cell(jGrafic, 5).Range.Text = studyingProcess.sessionStart.ToShortDateString() + "/\n" + studyingProcess.sessionEnd.ToShortDateString();
                    if (studyingProcess.practiceProductStart != null && studyingProcess.practiceTrainStart != null)
                    {
                        tableGrafik.Cell(jGrafic, 6).Range.Text = Convert.ToDateTime(studyingProcess.practiceProductStart).ToShortDateString() + "/\n" + Convert.ToDateTime(studyingProcess.practiceProductEnd).ToShortDateString() + "\n" + Convert.ToDateTime(studyingProcess.practiceTrainStart).ToShortDateString() + "/\n" + Convert.ToDateTime(studyingProcess.practiceTrainEnd).ToShortDateString();
                    }
                    else if (studyingProcess.practiceProductStart != null && studyingProcess.practiceTrainStart == null)
                    {
                        tableGrafik.Cell(jGrafic, 6).Range.Text = Convert.ToDateTime(studyingProcess.practiceProductStart).ToShortDateString() + "/\n" + Convert.ToDateTime(studyingProcess.practiceProductEnd).ToShortDateString();
                    }
                    else if (studyingProcess.practiceProductStart == null && studyingProcess.practiceTrainStart != null)
                    {
                        tableGrafik.Cell(jGrafic, 6).Range.Text = Convert.ToDateTime(studyingProcess.practiceTrainStart).ToShortDateString() + "/\n" + Convert.ToDateTime(studyingProcess.practiceTrainEnd).ToShortDateString();
                    }
                    tableGrafik.Cell(jGrafic, 7).Range.Text = studyingProcess.holidaysStart.ToShortDateString() + "/\n" + studyingProcess.holidaysEnd.ToShortDateString();
                    jGrafic++;
                }
                Microsoft.Office.Interop.Word.Table tableMeeting = application.ActiveDocument.Tables[20];
                int jMeeting = 2;
                foreach (Meeting meeting in DBobjects.Entities.Meeting.Where(p => p.idJournal == Journal.idJournal))
                {
                    if (jMeeting > 2)
                    {
                        tableMeeting.Rows.Add(ref missing);
                    }
                    tableMeeting.Rows[jMeeting].Cells[1].Range.Text = meeting.dateMeeting.ToShortDateString();
                    tableMeeting.Rows[jMeeting].Cells[2].Range.Text = meeting.questionMeeting;
                    String rezMeeting = "";
                    foreach (LackMeeting lackMeeting in DBobjects.Entities.LackMeeting.Where(p => p.idMeeting == meeting.idMeeting))
                    {
                        rezMeeting += lackMeeting.Student.ToString() + ";\n";
                    }
                    rezMeeting = rezMeeting.TrimEnd('\n', ' ');
                    tableMeeting.Rows[jMeeting].Cells[3].Range.Text = rezMeeting;
                    tableMeeting.Rows[jMeeting].Cells[4].Range.Text = meeting.decisionMeeting;
                    jMeeting++;
                }
                Microsoft.Office.Interop.Word.Table tableAttendance = application.ActiveDocument.Tables[21];
                int jAttendance = 2;
                foreach (Attendance attendance in DBobjects.Entities.Attendance.Where(p => p.idJournal == Journal.idJournal))
                {
                    if (jAttendance > 2)
                    {
                        tableAttendance.Rows.Add(ref missing);
                    }
                    tableAttendance.Rows[jAttendance].Cells[1].Range.Text = attendance.dateAttendance.ToShortDateString();
                    tableAttendance.Rows[jAttendance].Cells[2].Range.Text = attendance.Discipline.ToString() + "\n(" + attendance.OccupationStatus.ToString() + ")";
                    tableAttendance.Rows[jAttendance].Cells[3].Range.Text = attendance.fullNameTeach;
                    String rezAttendance = "";
                    foreach (LackAttendance lackAttendance in DBobjects.Entities.LackAttendance.Where(p => p.idAttendance == attendance.idAttendance))
                    {
                        rezAttendance += lackAttendance.Student.ToString() + ";\n";
                    }
                    rezAttendance = rezAttendance.TrimEnd('\n', ' ');
                    tableAttendance.Rows[jAttendance].Cells[4].Range.Text = rezAttendance;
                    jAttendance++;
                }

                Microsoft.Office.Interop.Word.Table tableTalkStudent = application.ActiveDocument.Tables[22];
                int jTalkStudent = 2;
                foreach (PrivateTalk privateTalk in DBobjects.Entities.PrivateTalk.Where(p => p.idJournal == Journal.idJournal))
                {
                    if (jTalkStudent > 2)
                    {
                        tableTalkStudent.Rows.Add(ref missing);
                    }
                    tableTalkStudent.Rows[jTalkStudent].Cells[1].Range.Text = privateTalk.datePrTalk.ToShortDateString();
                    tableTalkStudent.Rows[jTalkStudent].Cells[2].Range.Text = privateTalk.topicPrTalk;
                    String rezPrivTalk = "";
                    foreach (PrivTalkStudent privTalkStudent in DBobjects.Entities.PrivTalkStudent.Where(p => p.idPrTalk == privateTalk.idPrTalk))
                    {
                        rezPrivTalk += privTalkStudent.Student.ToString() + ";\n";
                    }
                    rezPrivTalk = rezPrivTalk.TrimEnd('\n', ' ');
                    tableTalkStudent.Rows[jTalkStudent].Cells[3].Range.Text = rezPrivTalk;
                    jTalkStudent++;
                }

                Microsoft.Office.Interop.Word.Table tableDisciplineComm = application.ActiveDocument.Tables[23];
                int jDisciplineComm = 2;
                foreach (Offense offense in DBobjects.Entities.Offense.Where(p => p.idJournal == Journal.idJournal))
                {
                    if (jDisciplineComm > 2)
                    {
                        tableDisciplineComm.Rows.Add(ref missing);
                    }
                    tableDisciplineComm.Rows[jDisciplineComm].Cells[1].Range.Text = offense.dateOffense.ToShortDateString();
                    tableDisciplineComm.Rows[jDisciplineComm].Cells[2].Range.Text = offense.numberProt;
                    tableDisciplineComm.Rows[jDisciplineComm].Cells[3].Range.Text = offense.causeOffense;
                    tableDisciplineComm.Rows[jDisciplineComm].Cells[4].Range.Text = offense.decisionOffense;
                    jDisciplineComm++;
                }
                Microsoft.Office.Interop.Word.Table tableMessage = application.ActiveDocument.Tables[24];
                int jMessage = 1;
                Microsoft.Office.Interop.Word.Table tableMeet = application.ActiveDocument.Tables[25];
                int jMeet = 1;
                Microsoft.Office.Interop.Word.Table tableDeduction = application.ActiveDocument.Tables[26];
                int jDeduction = 1;
                foreach (TalkParents talkParents in DBobjects.Entities.TalkParents.Where(p => p.idJournal == Journal.idJournal))
                {
                    String kins = "";
                    foreach (StructParentsTalc structParentsTalc in DBobjects.Entities.StructParentsTalc.Where(p => p.idTalkParents == talkParents.idTalkPar).ToList())
                    {
                        kins += structParentsTalc.Kin.fullNameKin + ",";
                    }
                    kins = kins.TrimEnd(',', ' ');
                    if (talkParents.TopicTalkParents.ToString() == "Письмо с уведомлением из деканата")
                    {
                        if (jMessage > 1)
                        {
                            tableMessage.Rows.Add(ref missing);
                        }
                        tableMessage.Rows[jMessage].Cells[1].Range.Text = talkParents.dateTalkPar.ToShortDateString() + " " + talkParents.topicTalc + ". Письмо отправлено: " + kins;
                        jMessage++;
                    }
                    else if (talkParents.TopicTalkParents.ToString() == "Личная встреча")
                    {
                        if (jMeet > 1)
                        {
                            tableMeet.Rows.Add(ref missing);
                        }
                        tableMeet.Rows[jMeet].Cells[1].Range.Text = talkParents.dateTalkPar.ToShortDateString() + " " + talkParents.topicTalc + ". Личная встреча состоялась с: " + kins;
                        jMeet++;
                    }
                    else if (talkParents.TopicTalkParents.ToString() == "Совместно с деканатом факультета и ректоратом решался вопрос об отчислении")
                    {
                        if (jDeduction > 1)
                        {
                            tableDeduction.Rows.Add(ref missing);
                        }
                        tableDeduction.Rows[jDeduction].Cells[1].Range.Text = talkParents.dateTalkPar.ToShortDateString() + " " + talkParents.topicTalc + ". Присутствующие родители: " + kins;
                        jDeduction++;
                    }
                }
                Microsoft.Office.Interop.Word.Table tableVisitHostel = application.ActiveDocument.Tables[27];
                int jVisitHostelHostel = 2;
                foreach (VisitHostel visitHostel in DBobjects.Entities.VisitHostel.Where(p => p.idJournal == Journal.idJournal))
                {
                    if (jVisitHostelHostel > 2)
                    {
                        tableVisitHostel.Rows.Add(ref missing);
                    }
                    tableVisitHostel.Rows[jVisitHostelHostel].Cells[1].Range.Text = visitHostel.dateVisitHostel.ToShortDateString();
                    tableVisitHostel.Rows[jVisitHostelHostel].Cells[2].Range.Text = visitHostel.causeVisitHostel;
                    String hostel = " ";
                    String rooms  = "";
                    foreach (ProvenRooms provenRooms in DBobjects.Entities.ProvenRooms.Where(p => p.idVisitHostel == visitHostel.idVisitHostel))
                    {
                        if (hostel.Contains(" " + provenRooms.Residence.Hostel.ToString() + ", ") == false)
                        {
                            hostel += provenRooms.Residence.Hostel.ToString() + ", ";
                        }
                        rooms += provenRooms.Residence.room + ", ";
                    }
                    hostel = hostel.TrimEnd(',', ' ');
                    rooms  = rooms.TrimEnd(',', ' ');
                    tableVisitHostel.Rows[jVisitHostelHostel].Cells[3].Range.Text = hostel;
                    tableVisitHostel.Rows[jVisitHostelHostel].Cells[4].Range.Text = rooms;
                    jVisitHostelHostel++;
                }
                Microsoft.Office.Interop.Word.Table tableAchivmentNauch = application.ActiveDocument.Tables[28];
                int jNauch = 1;
                Microsoft.Office.Interop.Word.Table tableAchivmentArtists = application.ActiveDocument.Tables[29];
                int jArtists = 1;
                Microsoft.Office.Interop.Word.Table tableAchivmentSports = application.ActiveDocument.Tables[30];
                int jSports = 1;
                Microsoft.Office.Interop.Word.Table tableAchivmentOther = application.ActiveDocument.Tables[31];
                int jOther = 1;
                foreach (Event events in DBobjects.Entities.Event.Where(p => p.idJournal == Journal.idJournal))
                {
                    foreach (AchivementStudent achivementStudent in DBobjects.Entities.AchivementStudent.Where(p => p.idEvent == events.idEvent).ToList())
                    {
                        if (events.TypeOfEvent.ToString() == "Научно-исследовательская работа")
                        {
                            if (jNauch > 1)
                            {
                                tableAchivmentNauch.Rows.Add(ref missing);
                            }
                            tableAchivmentNauch.Rows[jNauch].Cells[1].Range.Text = events.dateEvent.ToShortDateString() + " " + events.nameEvent + " Участник: " + achivementStudent.Student.ToString() + ". Руководитель: " + achivementStudent.fullNameSupervis + ", Тема работы: " + achivementStudent.topicWork + ". (" + achivementStudent.topicAchivment + ")";
                            jNauch++;
                        }
                        else if (events.TypeOfEvent.ToString() == "Художественная самодеятельность")
                        {
                            if (jArtists > 1)
                            {
                                tableAchivmentArtists.Rows.Add(ref missing);
                            }
                            tableAchivmentArtists.Rows[jArtists].Cells[1].Range.Text = events.dateEvent.ToShortDateString() + " " + events.nameEvent + ". Участники: " + achivementStudent.Student.ToString() + ". (" + achivementStudent.topicAchivment + ")";
                            jArtists++;
                        }
                        else if (events.TypeOfEvent.ToString() == "Спортивное мероприятие")
                        {
                            if (jSports > 1)
                            {
                                tableAchivmentSports.Rows.Add(ref missing);
                            }
                            tableAchivmentSports.Rows[jSports].Cells[1].Range.Text = events.dateEvent.ToShortDateString() + " " + events.nameEvent + ". Участник: " + achivementStudent.Student.ToString() + ". (" + achivementStudent.topicAchivment + ")";
                            jSports++;
                        }
                        else
                        {
                            if (jOther > 1)
                            {
                                tableAchivmentOther.Rows.Add(ref missing);
                            }
                            tableAchivmentOther.Rows[jOther].Cells[1].Range.Text = "Тип мероприятия: " + events.TypeOfEvent.ToString() + " " + events.dateEvent.ToShortDateString() + " " + events.nameEvent + ". Участник: " + achivementStudent.Student.ToString() + ". (" + achivementStudent.topicAchivment + ")";
                            jOther++;
                        }
                    }
                }
                saveFileDialogJournal.FileName = "Журнал группы " + Journal.Group.numberGroup + " за " + Journal.courceGroup.ToString() + " курс.docx";
                if (saveFileDialogJournal.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }
                // получаем выбранный файл
                object SaveAsFile = saveFileDialogJournal.FileName;
                document.SaveAs2(SaveAsFile, missing, missing, missing);
                document.Close(ref falseObj, ref missing, ref missing);
                application.Quit(ref missing, ref missing, ref missing);
                document = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
                application = null;
                //Открываем документ для просмотра.
                System.Diagnostics.Process.Start(SaveAsFile.ToString());
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show(ex.Message);
                document.Close(ref falseObj, ref missing, ref missing);
                application.Quit(ref missing, ref missing, ref missing);
                document    = null;
                application = null;
                this.Cursor = Cursors.Default;
                application.Quit();
            }
            this.Cursor = Cursors.Default;
        }
Ejemplo n.º 18
0
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word.Document    doc = null;
            //将要导出的新word文件名
            string physicNewFile = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc";

            try
            {
                app = new Microsoft.Office.Interop.Word.Application();                   //创建word应用程序
                object fileName = System.Windows.Forms.Application.StartupPath + Change; //Year1;//模板文件
                app.Visible = true;
                //打开模板文件
                object oMissing = System.Reflection.Missing.Value;
                doc = app.Documents.Open(ref fileName,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);



                Word.Range range = doc.Paragraphs.Last.Range;
                //object tmp = "BT_CREATE";
                //Word.Range range = app.ActiveDocument.Bookmarks.get_Item(ref tmp).Range;

                //Microsoft.Office.Interop.Word.Range range = app.Selection.Range;
                Microsoft.Office.Interop.Word.Table table = app.Selection.Tables.Add(range, 2, 4, ref oMissing, ref oMissing);
                //设置表格的字体大小粗细
                table.Range.Font.Size = 10;
                table.Range.Font.Bold = 0;

                //设置表格标题
                int rowIndex = 1;
                table.Cell(rowIndex, 1).Range.Text = "班级";
                table.Cell(rowIndex, 2).Range.Text = "姓名";
                table.Cell(rowIndex, 3).Range.Text = "成绩";
                table.Cell(rowIndex, 4).Range.Text = "班主任";

                //循环数据创建数据行

                table.Cell(2, 1).Range.Text = "1";    //班级
                table.Cell(2, 4).Range.Text = "4";    //人数
                table.Cell(2, 2).Range.Text = "2";    //班主任
                table.Cell(2, 3).Range.Text = "3";



                //为表格划线
                range.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle        = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle       = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle      = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle     = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle   = WdLineStyle.wdLineStyleSingle;

                object count = 14;
                //object WdLine = Word.WdUnits.wdLine;//换一行;
                //app.Selection.MoveDown(ref WdLine, ref count, ref oMissing);//移动焦点
                //
                object unit;
                unit = Word.WdUnits.wdStory;
                app.Selection.EndKey(ref unit, ref oMissing);
                app.Selection.TypeParagraph();    //插入段落

                app.Selection.Text = "aaaa";


                Word.Range range1 = doc.Paragraphs.Last.Range;
                //object tmp = "BT_CREATE";
                //Word.Range range = app.ActiveDocument.Bookmarks.get_Item(ref tmp).Range;

                //Microsoft.Office.Interop.Word.Range range = app.Selection.Range;
                Microsoft.Office.Interop.Word.Table table1 = app.Selection.Tables.Add(range1, 5, 5, ref oMissing, ref oMissing);
                //设置表格的字体大小粗细
                table1.Range.Font.Size = 10;
                table1.Range.Font.Bold = 0;


                //为表格划线
                range1.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle        = WdLineStyle.wdLineStyleSingle;
                range1.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle       = WdLineStyle.wdLineStyleSingle;
                range1.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle      = WdLineStyle.wdLineStyleSingle;
                range1.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle     = WdLineStyle.wdLineStyleSingle;
                range1.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
                range1.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle   = WdLineStyle.wdLineStyleSingle;


                //设置表格标题
                int rowIndex1 = 1;
                table1.Cell(rowIndex1, 1).Range.Text = "班级";
                table1.Cell(rowIndex1, 2).Range.Text = "姓名";
                table1.Cell(rowIndex1, 3).Range.Text = "成绩";
                table1.Cell(rowIndex1, 4).Range.Text = "班主任";
                table1.Cell(rowIndex1, 5).Range.Text = "112233";

                //循环数据创建数据行

                table1.Cell(2, 1).Range.Text = "一";    //班级
                table1.Cell(2, 4).Range.Text = "四";    //人数
                table1.Cell(2, 2).Range.Text = "二";    //班主任
                table1.Cell(2, 3).Range.Text = "三";
                table1.Cell(2, 5).Range.Text = "三1";



                //对替换好的word模板另存为一个新的word文档
                doc.SaveAs(System.Windows.Forms.Application.StartupPath + "\\ExcelHeaderTemplate\\" + physicNewFile,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                //这边为了捕获Response.End引起的异常
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭word文档
                }
                if (app != null)
                {
                    app.Quit();//退出word应用程序
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 导出Word 的方法
        /// </summary>
        private void tslExport_Word()
        {
            #region 方法一
            SaveFileDialog sfile = new SaveFileDialog();
            sfile.AddExtension = true;
            sfile.DefaultExt   = ".doc";
            sfile.Filter       = "(*.doc)|*.doc";
            sfile.FileName     = "理文检测系统车辆质检统计Word报表" + DateTime.Now.ToShortDateString();
            if (sfile.ShowDialog() == DialogResult.OK)
            {
                object path = sfile.FileName;
                Object none = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Application wordApp  = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
                //建立表格
                Microsoft.Office.Interop.Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, dgvCarStatisticsQC.Rows.Count + 1, dgvCarStatisticsQC.Columns.Count, ref none, ref none);
                try
                {
                    for (int i = 0; i < dgvCarStatisticsQC.Columns.Count; i++)//设置标题
                    {
                        table.Cell(0, i + 1).Range.Text = dgvCarStatisticsQC.Columns[i].HeaderText;
                    }
                    //for (int i = 0; i < dgvCarStatisticsQC.Rows.Count; i++)//填充数据
                    //{
                    //    i++;
                    //    for (int j = 0; j < dgvCarStatisticsQC.Columns.Count; j++)
                    //    {
                    //        //if (dgvCarStatisticsQC[i-1, j].Value != null)
                    //        //{
                    //            table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC.Rows[i-1].Cells[j].Value.ToString();
                    //        //}
                    //    }
                    //}

                    for (int i = 1; i <= dgvCarStatisticsQC.Rows.Count; i++)       //填充数据
                    {
                        for (int j = 0; j < dgvCarStatisticsQC.Columns.Count; j++) //dgvCarStatisticsQC.Columns.Count
                        {
                            //table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                            if (dgvCarStatisticsQC[j, i - 1].Value != null)
                            {
                                // table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                                table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                            }
                            else
                            {
                                table.Cell(i + 1, j + 1).Range.Text = "";
                            }
                        }
                    }

                    document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
                    document.Close(ref none, ref none, ref none);
                    MessageBox.Show("导出数据成功!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    wordApp.Quit(ref none, ref none, ref none);
                }
            }
            #endregion

            #region 方法二
            //Word.Document mydoc = new Word.Document();
            //Word.Table mytable = null;
            //Word.Selection mysel;
            //Object myobj;

            ////建立Word对象
            //Word.Application word = new Word.Application();
            //myobj = System.Reflection.Missing.Value;
            //mydoc = word.Documents.Add(ref myobj, ref myobj, ref myobj, ref myobj);
            //word.Visible = true;
            //mydoc.Select();
            //mysel = word.Selection;
            ////将数据生成Word表格文件
            //mytable = mydoc.Tables.Add(mysel.Range, this.dgvCarStatisticsQC.RowCount, this.dgvCarStatisticsQC.ColumnCount, ref myobj, ref myobj);
            ////设置列宽
            //mytable.Columns.SetWidth(30, Word.WdRulerStyle.wdAdjustNone);
            ////输出列标题数据
            //for (int i = 0; i < this.dgvCarStatisticsQC.ColumnCount; i++)
            //{
            //    mytable.Cell(1, i + 1).Range.InsertAfter(this.dgvCarStatisticsQC.Columns[i].HeaderText);
            //}
            ////输出控件中的记录
            //for (int i = 0; i < this.dgvCarStatisticsQC.RowCount - 1; i++)
            //{
            //    for (int j = 0; j < this.dgvCarStatisticsQC.ColumnCount; j++)
            //    {
            //        mytable.Cell(i + 2, j + 1).Range.InsertAfter(this.dgvCarStatisticsQC[j, i].Value.ToString());
            //    }
            //}
            #endregion
        }
Ejemplo n.º 20
0
        private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (bgWorker1.CancellationPending)
                {
                    e.Cancel = true;
                }
                else
                {
                    //Lấy thông tin từ class static

                    if (InfoTest.DanhSachNhomCauHoi.Count == 0)
                    {
                        //MessageBox.Show("dto moi them = " + InfoTest.DanhSachNhomCauHoi[0].DuongDan + "; điểm = " + InfoTest.DanhSachNhomCauHoi[0].Diem.ToString());
                        MessageBox.Show("Không có dữ liệu", "Thông tin", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    //
                    string sKyThi           = InfoTest.sKyThi;
                    string sMonThi          = InfoTest.sMonThi;
                    string sDoiTuong        = InfoTest.sDoiTuong;
                    string sHinhThucThi     = InfoTest.sHinhThucThi;
                    string sThoiGian        = InfoTest.sThoiGian;
                    string sNgayThangNamThi = InfoTest.sNgayThi + "/" + InfoTest.sThangThi + "/" + InfoTest.sNamThi;
                    int    iSoDe            = InfoTest.iSoDe;//_soDe là số đề cần tạo ra  Được tính từ MaDeTu và MaDeDen
                    //
                    ArrayList dsCauHoiBoDe = new ArrayList();
                    int       iSoCauMax;                                                    //n là số câu max trong danh sách câu nhóm 1
                    int       k = 0;
                    int       iPhanTramCongViec = 0;                                        //j là số % công việc đang thực hiện
                    //TẠO DANH SACH CÂU HỎI CHO BỘ ĐỀ ĐẢM BẢO YÊU CẦU
                    for (int iNhom = 0; iNhom < InfoTest.DanhSachNhomCauHoi.Count; iNhom++) //Làm từng đề lần lượt
                    {
                        iSoCauMax = InfoTest.DanhSachNhomCauHoi[iNhom].SoCau;
                        List <int> tmp = CreateListTest(iSoCauMax, iSoDe, k);
                        //string ds1 = "";
                        //foreach (int m in tmp)
                        //{
                        //    ds1 = ds1 + m.ToString() + " ";
                        //}
                        //MessageBox.Show("DS câu nhóm " + iNhom.ToString() +": " + ds1);
                        dsCauHoiBoDe.Add(tmp);
                        k++;
                    }
                    //% mở đề thi mẫu
                    bgWorker1.ReportProgress(5);
                    //Mở MS Word rồi tạo file đề thi để chuẩn bị copy nội dung
                    Word.Application wordApp = new Word.Application();
                    wordApp.Visible = false;
                    object filename = InfoTest.sThuMucDeMau + "\\DeThiMau3.docx";

                    List <int>    processesbeforegen = getRunningProcesses();
                    Word.Document docDeThiMau        = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                                              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);;

                    Word.Document emptyDoc = null;  //Tạo tệp tin đề thi
                    emptyDoc = wordApp.Documents.Add();
                    Word.Document emptyDoc1 = null; //Tạo tệp tin đáp án đề thi
                    emptyDoc1 = wordApp.Documents.Add();
                    string sTenDe = "";
                    for (int _iSoDe = 0; _iSoDe < iSoDe; _iSoDe++) //Xét từng đề
                    {
                        //% Tạo đề thi thứ nhất
                        bgWorker1.ReportProgress((_iSoDe + 1) * 100 / iSoDe);
                        iPhanTramCongViec      = iPhanTramCongViec + 100 / iSoDe;//Cập nhật % hiện đã hoàn thành
                        InfoTest.iDeThiDangTao = _iSoDe + 1;
                        //
                        docDeThiMau.Activate();
                        //Copy nội dung file mẫu
                        docDeThiMau.Sections.First.Range.Copy();
                        //Paste vào tệp tin ĐỀ THI
                        emptyDoc.Activate();
                        oRng   = emptyDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                        oPara2 = emptyDoc.Content.Paragraphs.Add(ref oRng);
                        oPara2.Range.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdFormatOriginalFormatting); //paste tiêu đề và giữa nguyên định dạng
                        //Find and replace:
                        sTenDe = InfoTest.DanhSachTenDeThi[_iSoDe];                                                           //Lấy tên đề trong danh sách tên đề
                        //
                        while (sTenDe.Length < 2)
                        {
                            sTenDe = '0' + sTenDe;
                        }
                        this.FindAndReplace(wordApp, "$KYTHI$", sKyThi);
                        this.FindAndReplace(wordApp, "$MONTHI$", sMonThi);
                        this.FindAndReplace(wordApp, "$DOITUONG$", sDoiTuong);
                        this.FindAndReplace(wordApp, "$HINHTHUCTHI$", sHinhThucThi);
                        this.FindAndReplace(wordApp, "$THOIGIAN$", sThoiGian);
                        this.FindAndReplace(wordApp, "$NGAYTHI$", sNgayThangNamThi);
                        this.FindAndReplace(wordApp, "$MADE$", sTenDe.ToString());
                        //Paste vào tệp tin ĐÁP ÁN ĐỀ THI
                        emptyDoc1.Activate();
                        oRng   = emptyDoc1.Bookmarks.get_Item(ref oEndOfDoc).Range;
                        oPara2 = emptyDoc1.Content.Paragraphs.Add(ref oRng);
                        oPara2.Range.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdFormatOriginalFormatting); //paste tiêu đề và giữa nguyên định dạng
                        //Find and replace:
                        sTenDe = InfoTest.DanhSachTenDeThi[_iSoDe];                                                           //Lấy tên đề trong danh sách tên đề
                        //
                        while (sTenDe.Length < 3)
                        {
                            sTenDe = '0' + sTenDe;
                        }
                        this.FindAndReplace(wordApp, "$KYTHI$", sKyThi);
                        this.FindAndReplace(wordApp, "$MONTHI$", sMonThi);
                        this.FindAndReplace(wordApp, "$DOITUONG$", sDoiTuong);
                        this.FindAndReplace(wordApp, "$HINHTHUCTHI$", sHinhThucThi);
                        this.FindAndReplace(wordApp, "$THOIGIAN$", sThoiGian);
                        this.FindAndReplace(wordApp, "$NGAYTHI$", sNgayThangNamThi);
                        this.FindAndReplace(wordApp, "$MADE$", sTenDe.ToString());
                        //Paste nội dung chi tiết
                        for (int i = 0; i < InfoTest.DanhSachNhomCauHoi.Count; i++)            //Mở từng nhóm file
                        {
                            object        _fileNhom = InfoTest.DanhSachNhomCauHoi[i].DuongDan; //Lấy đường dẫn nhóm file
                            Word.Document docNhom   = null;
                            docNhom = wordApp.Documents.Open(ref _fileNhom, ref missing, ref readOnly,
                                                             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);
                            docNhom.Activate();
                            //---------------Paste ĐỀ THI
                            List <int> tt = (List <int>)dsCauHoiBoDe[i];
                            docNhom.Tables[tt[_iSoDe]].Rows[1].Cells[1].Range.Copy();//Lấy cùng vị trí câu trong từng nhóm câu hỏi
                            // Select the last table.
                            // For this demo, the table has size of 3*4 (row * column).
                            int totalTables = emptyDoc.Tables.Count;
                            Microsoft.Office.Interop.Word.Table tab   = emptyDoc.Tables[totalTables];
                            Microsoft.Office.Interop.Word.Range range = tab.Range;
                            // Moves the cursor to the first cell of target row.
                            range.Start = tab.Rows[tab.Rows.Count].Cells[1].Range.Start;
                            range.End   = range.Start;
                            // Paste values to target row.
                            range.Paste();
                            // Insert a new row after the last row.
                            if (i != InfoTest.DanhSachNhomCauHoi.Count - 1)
                            {
                                tab.Rows.Add(ref missing);
                            }
                            //-------------Kết thúc Paste ĐỀ THI
                            //-------------------------------------------------
                            //---------------Paste ĐÁP ÁN ĐỀ THI
                            List <int> tt1 = (List <int>)dsCauHoiBoDe[i];
                            docNhom.Tables[tt1[_iSoDe]].Range.Copy();//Lấy cùng vị trí câu trong từng nhóm câu hỏi
                            // Select the last table.
                            // For this demo, the table has size of 3*4 (row * column).
                            int totalTables1 = emptyDoc1.Tables.Count;
                            Microsoft.Office.Interop.Word.Table tab1   = emptyDoc1.Tables[totalTables];
                            Microsoft.Office.Interop.Word.Range range1 = tab1.Range;
                            // Moves the cursor to the first cell of target row.
                            range1.Start = tab1.Rows[tab1.Rows.Count].Cells[1].Range.Start;
                            range1.End   = range1.Start;
                            // Paste values to target row.
                            range1.Paste();
                            //-------------Kết thúc Paste ĐÁP ÁN ĐỀ THI

                            //
                            #region "Sao chép chỉ nội dung của cell"
                            //List<int> tt = (List<int>)dsCauHoiBoDe[i];
                            //var copyFrom = docNhom.Tables[tt[_iSoDe]].Rows[1].Cells[1].Range;//Lấy cùng vị trí câu trong từng nhóm câu hỏi
                            //int start = emptyDoc.Content.End - 1;
                            //int end = emptyDoc.Content.End;
                            //var copyTo = emptyDoc.Range(start, end);
                            //copyFrom.MoveEnd(Microsoft.Office.Interop.Word.WdUnits.wdCharacter, -1);
                            //copyTo.FormattedText = copyFrom.FormattedText;
                            #endregion

                            //----------------ĐỀ THI_Thay thế chữ "Câu hỏi" bằng "Câu 1 (2 điểm)"
                            string tenCauHoi = "";
                            int    tenCau;
                            tenCau    = i + 1;
                            tenCauHoi = InfoTest.sTenCau + " " + tenCau.ToString() + " (" + InfoTest.DanhSachNhomCauHoi[i].Diem + " điểm)";
                            emptyDoc.Activate();
                            this.FindAndReplace(wordApp, "Câu hỏi", tenCauHoi);
                            //-------------------ĐỀ THI-kết thúc
                            //----------------ĐÁP ÁN ĐỀ THI_Thay thế chữ "Câu hỏi" bằng "Câu 1 (2 điểm)"

                            emptyDoc1.Activate();
                            this.FindAndReplace(wordApp, "Câu hỏi", tenCauHoi);
                            //-------------------ĐÁP ÁN ĐỀ THI-kết thúc
                            ////Thêm 1 mark dòng
                            //copyTo.InsertParagraphAfter();
                            //copyTo.SetRange(end, end);
                            //Close Document:
                            docNhom.Close(ref missing, ref missing, ref missing);
                            //Kết thúc đọc file nhóm
                        }
                        //-----------ĐỀ THI - Thêm giải thích
                        oRng = emptyDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                        if (InfoTest.sGiaiThich != "")                         //Nếu có thêm giải thích
                        {
                            oPara = emptyDoc.Content.Paragraphs.Add(ref oRng); //add paragraph at end of document
                            //oPara.Range.Font.Name = "Arial";
                            oPara.Range.Text        = InfoTest.sGiaiThich;     //"Không được sử dụng tài liệu"; //add some text in paragraph
                            oPara.Alignment         = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                            oPara.Range.Font.Bold   = 1;
                            oPara.Format.SpaceAfter = 10; //define some style
                            oPara.Range.InsertParagraphAfter();
                        }
                        if (_iSoDe != iSoDe - 1)
                        {
                            ////Thêm 1 ngắt trang, chuyển sang đề tiếp theo
                            wrdRng = emptyDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                            wrdRng.InsertBreak(ref oPageBreak);
                        }
                        //-------------kết thúc ĐỀ THI - Thêm giải thích
                        //-----------ĐÁP ÁN ĐỀ THI - Thêm giải thích
                        oRng = emptyDoc1.Bookmarks.get_Item(ref oEndOfDoc).Range;
                        if (InfoTest.sGiaiThich != "")                          //Nếu có thêm giải thích
                        {
                            oPara = emptyDoc1.Content.Paragraphs.Add(ref oRng); //add paragraph at end of document
                            //oPara.Range.Font.Name = "Arial";
                            oPara.Range.Text        = InfoTest.sGiaiThich;      //"Không được sử dụng tài liệu"; //add some text in paragraph
                            oPara.Alignment         = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                            oPara.Range.Font.Bold   = 1;
                            oPara.Format.SpaceAfter = 10; //define some style
                            oPara.Range.InsertParagraphAfter();
                        }
                        if (_iSoDe != iSoDe - 1)
                        {
                            ////Thêm 1 ngắt trang, chuyển sang đề tiếp theo
                            wrdRng = emptyDoc1.Bookmarks.get_Item(ref oEndOfDoc).Range;
                            wrdRng.InsertBreak(ref oPageBreak);
                        }
                        //-------------kết thúc ĐÁP ÁN ĐỀ THI - Thêm giải thích
                    }
                    //Save as: filename ĐỀ THI
                    if (!System.IO.Directory.Exists(InfoTest.sViTriLuuDeThi))
                    {
                        InfoTest.sViTriLuuDeThi = InfoTest.sThuMucGoc;
                    }
                    string name   = sMonThi + string.Format("{0: ddMMyyyyhhmmss}", DateTime.Now);
                    object saveAs = InfoTest.sViTriLuuDeThi + "\\" + name + ".docx";
                    emptyDoc.SaveAs2(ref saveAs, 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);
                    emptyDoc.Close(ref missing, ref missing, ref missing);
                    //Save as: filename ĐÁP ÁN ĐỀ THI
                    object saveAs1 = InfoTest.sViTriLuuDeThi + "\\" + name + "_dap_an" + ".docx";
                    emptyDoc1.SaveAs2(ref saveAs1, 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);
                    emptyDoc1.Close(ref missing, ref missing, ref missing);
                    //
                    docDeThiMau.Close(); //Đóng đề thi mẫu
                    wordApp.Quit();      //Thoát MS Word
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi 1: " + ex.Message + " source:" + ex.Source);
            }
            finally
            {
                processesaftergen = getRunningProcesses();
                killProcesses(processesbeforegen, processesaftergen);
            }
        }
Ejemplo n.º 21
0
        //экспорт в шаблон Word
        private void button6_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("" + My.oborudovanie.ToString() );
            //if (textBox2.Text == "")
            //{
            //    MessageBox.Show("Не выбран(ы) испытатель(ли)!");
            //    return;
            //}

            //MessageBox.Show("" + My.poveritelListLength);
            //dbCon.Close();
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    doc = new Microsoft.Office.Interop.Word.Document();
            object missing = Type.Missing;

            //Объявляем новый экземпляр класса Stopwatch
            //запускаем
            Stopwatch testStopwatch = new Stopwatch();

            testStopwatch.Start();

            if (dataGridView1.Rows.Count != 0)
            {
                object fileName   = Directory.GetCurrentDirectory() + @"\ОА\tmpl.doc";
                object falseValue = false;
                object trueValue  = true;

                doc = app.Documents.Open(ref fileName, ref missing, ref falseValue,
                                         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);
                //app.Visible = true;

                //exception();
                //string[] txt = { label1.Text, DateTime.Now.ToLongDateString(), label2.Text, label3.Text, /*label4.Text,*/ label5.Text, label4.Text, label6.Text, label23.Text, label7.Text, label8.Text, label9.Text, label10.Text, label11.Text, label12.Text, /*label13.Text*/ label18.Text, label19.Text, label20.Text, label21.Text, label22.Text, label14.Text, label15.Text };
                string[] txt     = { label1.Text, label26.Text, /*DateTime.Now.ToLongDateString(),*/ label2.Text, label3.Text, /*label4.Text,*/ label5.Text, label4.Text, label6.Text, label23.Text, label7.Text, label8.Text, label9.Text, label10.Text, label11.Text, label12.Text, label13.Text /*, label18.Text, label19.Text, label20.Text, label21.Text, label22.Text*/ /*, label14.Text, label15.Text*/ };
                string[] FindObj = { "$num$", "$date$", /*"$date$",*/ "$zakazchik$", "$adress_zakazchika$", /*"$postavshik$",*/ "$name_izgotov$", "$adress_izgotov$", "$product_name$", "$product_group$", "$name$", "$proba$", "$date_time_postuplenia$", "$date_exe$", "$osnovanie$", "$nd$", "$conditions$" /*, "$temperature$", "$vlazhnost$","$davlenie$", "$elmagpole$", "$magpole$"*/ /*, "$dolznost$", "$sotrudnik$"*/ };

                int n = 0;
                while (n < FindObj.Length)
                {
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM    = FindObj[n];
                    object replaceWithNUM = txt[n];
                    object replaceNUM     = 2;

                    app.Selection.Find.Execute(ref findTextNUM, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM, ref replaceNUM, ref missing, ref missing, ref missing, ref missing);
                    n++;
                }
                n = 0;


                //string poveritelListFind = "$poveritelList$";
                for (int nn = 0; nn < My.poveritelListLength; nn++)
                {
                    if (My.poveritelList[nn] == "")
                    {
                        nn++;
                    }
                    else
                    {
                        textBox2.AppendText(My.poveritelList[nn] + "\r\r");
                    }
                }

                //Очищаем параметры поиска
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Replacement.ClearFormatting();

                //Задаём параметры замены и выполняем замену.
                object findTextNUM2    = "$poveritelList$";
                object replaceWithNUM2 = textBox2.Text;
                object replaceNUM2     = 2;

                app.Selection.Find.Execute(ref findTextNUM2, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing,
                                           ref replaceWithNUM2, ref replaceNUM2, ref missing, ref missing, ref missing, ref missing);


                //string oborudovanieListFind = "$oborudovanie$";
                for (int nn = 0; nn < My.oborudovanieListLength; nn++)
                {
                    //textBox2.AppendText(My.poveritelList[nn] + "\r\r");
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM3    = "$oborudovanie$";
                    object replaceWithNUM3 = "- " + My.oborudovanieList[nn] + ";\r$oborudovanie$";
                    object replaceNUM3     = 2;

                    app.Selection.Find.Execute(ref findTextNUM3, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM3, ref replaceNUM3, ref missing, ref missing, ref missing, ref missing);
                }

                //Задаём параметры замены и выполняем замену.
                object findTextNUM4    = "$oborudovanie$";
                object replaceWithNUM4 = "";
                object replaceNUM4     = 2;

                app.Selection.Find.Execute(ref findTextNUM4, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing,
                                           ref replaceWithNUM4, ref replaceNUM4, ref missing, ref missing, ref missing, ref missing);

                Microsoft.Office.Interop.Word.Table table = doc.Tables[2];

                int i;

                for (i = 1; i < dataGridView1.Rows.Count + 1; i++)
                {
                    table.Rows.Add();
                    table.Cell(i + 2, 1).Range.Text = i.ToString();          //нумерация

                    for (int j = 1; j < dataGridView1.ColumnCount - 1; j++)  //цикл вставки dGV
                    {
                        //table.Cell(i + 2, j + 1).Range.Text = dataGridView1.Rows[i - 1].Cells[j].Value.ToString();
                        table.Cell(i + 3, j + 1).Range.Text = dataGridView1.Rows[i - 1].Cells[j].Value.ToString();
                    }
                }

                //количество страниц/листов
                Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
                double           x    = doc.ComputeStatistics(stat, ref missing); //страницы
                string           y    = Math.Ceiling(x / 2).ToString("G17");      //листы
                //label16.Text = x.ToString("G17");

                //поиск и вставка x&y
                string[] xy     = { x.ToString("G17"), y };
                string[] Findxy = { "$x$", "$y$" };

                while (n < Findxy.Length)
                {
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM    = Findxy[n];
                    object replaceWithNUM = xy[n];
                    object replaceNUM     = 2;

                    app.Selection.Find.Execute(ref findTextNUM, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM, ref replaceNUM, ref missing, ref missing, ref missing, ref missing);
                    n++;
                }
                n = 0;

                DialogResult res = MessageBox.Show("Экспорт завершен. При нажатии ДА будет открыт сгенерированный файл, при нажатии НЕТ произойдет автоматическое сохранение файла и его открытие.", "Экспорт в Excel", MessageBoxButtons.YesNoCancel);

                if (res == DialogResult.Yes)    //открытие сгенерированного файла
                {
                    try
                    {
                        //Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ОА\tmpl.doc";
                        //object newfileName = Directory.GetCurrentDirectory() + @"\ОА\протокол №" + label1.Text + ".doc";
                        app.Visible = true;

                        //doc = app.Documents.Open(ref fileName, ref missing, ref trueValue,
                        //                         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);
                        //// Закрываем родительскую форму
                        //Hide();
                        MessageBox.Show("Экспорт успешно завершен, протокол открыт. При необходимости, сохраните протокол.");

                        /*
                         * string lastNumDir = Directory.GetCurrentDirectory() + @"\ОА\последний_номер.txt";
                         * string lastNumUPD = label1.Text;
                         * System.IO.File.WriteAllText(lastNumDir, lastNumUPD);
                         */
                    }
                    catch
                    {
                        MessageBox.Show("ooooops...! что-то пошло не так. Пожалуйста обратитесь в службу поддержки");
                    }
                }

                if (res == DialogResult.No)     //автоматическое сохранение файла
                {
                    try
                    {
                        object Target  = (Directory.GetCurrentDirectory() + @"\ОА\Протоколы\" + label1.Text + ".doc"); // куда сохранить
                        object format_ = Word.WdSaveFormat.wdFormatDocumentDefault;
                        //Сохранение файла
                        doc.SaveAs(ref Target, ref format_,
                                   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);

                        //object falseValue = false;
                        //object trueValue = true;

                        doc = app.Documents.Open(ref Target, ref missing, ref falseValue,
                                                 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);
                        ///
                        ///колонтитулы
                        ///

                        //верний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekFirstPageHeader;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                            doc.ActiveWindow.Selection.TypeText("");
                            doc.ActiveWindow.Selection.Fields.Add(s.Range);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //верхний колонтитул
                        //остальные страницы
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                            doc.ActiveWindow.Selection.TypeText("ФБУ «Нижегородский ЦСМ» ИЦ «НИЖЕГОРОДСИСПЫТАНИЯ»          Протокол №" + label1.Text + " от " + label26.Text);
                            doc.ActiveWindow.Selection.Fields.Add(s.Range);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //нижний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            //нижний колонтитул
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            // код для номеров страницы
                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekFirstPageFooter;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                            doc.ActiveWindow.Selection.TypeText("страница ");
                            object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; //текущая страница
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref CurrentPage, ref oMissing, ref oMissing);

                            doc.ActiveWindow.Selection.TypeText(" из ");
                            object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; //всего страниц
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref TotalPages, ref oMissing, ref oMissing);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //нижний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            //нижний колонтитул
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            // код для номеров страницы
                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryFooter;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                            doc.ActiveWindow.Selection.TypeText("страница ");
                            object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; //текущая страница
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref CurrentPage, ref oMissing, ref oMissing);

                            doc.ActiveWindow.Selection.TypeText(" из ");
                            object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; //всего страниц
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref TotalPages, ref oMissing, ref oMissing);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        app.Visible = true;

                        MessageBox.Show("Экспорт успешно завершен, протокол сохранен под номером " + label1.Text);
                    }
                    catch
                    {
                        MessageBox.Show("ooooops...! что-то пошло не так. Пожалуйста обратитесь в службу поддержки");
                    }
                }

                if (res == DialogResult.Cancel) //отмена
                {
                    MessageBox.Show("Сохранение результатов экспорта отменено");
                    ((Microsoft.Office.Interop.Word._Application)app).Quit(false, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
                }
                //Останавливаем
                testStopwatch.Stop();

                //Теперь можем смотреть время выполнения операции
                TimeSpan tSpan; tSpan = testStopwatch.Elapsed;
                //MessageBox.Show("Время выполнения операции - " + tSpan.ToString()); //время выполнения операции
            }
            else
            {
                MessageBox.Show("Не открыта таблица для запроса");
            }
            exit = false;



            Hide();
            Form3 form3 = new Form3();

            form3.Show();
        }
Ejemplo n.º 22
0
        public void InitRead(string Template, Dictionary <string, string> datas, string saveFileName, DataView dv)
        {
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word.Document    doc = null;

            try
            {
                app = new Microsoft.Office.Interop.Word.Application();                     //创建word应用程序
                object fileName = System.Windows.Forms.Application.StartupPath + Template; //Year1;//模板文件
                app.Visible = false;
                //打开模板文件
                object oMissing = System.Reflection.Missing.Value;
                doc = app.Documents.Open(ref fileName,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                foreach (var item in datas)
                {
                    app.Selection.Find.Replacement.ClearFormatting();
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Text             = item.Key;   //需要被替换的文本
                    app.Selection.Find.Replacement.Text = item.Value; //替换文本

                    //执行替换操作
                    app.Selection.Find.Execute(
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing, ref oMissing,
                        ref oMissing, ref replace,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing);
                }
                string imageName = downLoadSignature();
                //电子签章是否存在
                if (!string.IsNullOrEmpty(imageName))
                {
                    //标签
                    object bookMark = "SIGNATURE";
                    if (app.ActiveDocument.Bookmarks.Exists(Convert.ToString(bookMark)) == true)
                    {
                        //图片
                        string replacePic = String.Format(@"{0}\{1}", defaultDirectory.Signature, imageName);
                        //定义该插入图片是否为外部链接
                        object linkToFile = true;
                        //定义插入图片是否随word文档一起保存
                        object saveWithDocument = true;
                        object Nothing          = System.Reflection.Missing.Value;
                        //查找书签
                        app.ActiveDocument.Bookmarks.get_Item(ref bookMark).Select();
                        //设置图片位置
                        app.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                        //在书签的位置添加图片
                        InlineShape inlineShape = app.Selection.InlineShapes.AddPicture(replacePic, ref linkToFile, ref saveWithDocument, ref Nothing);
                        //设置图片大小
                        inlineShape.Width  = 100;
                        inlineShape.Height = 100;
                    }
                }
                System.Data.DataView dt = dv;


                object     tmp   = "BT_CREATE";                                          //WORD中创建标签
                Word.Range range = app.ActiveDocument.Bookmarks.get_Item(ref tmp).Range; //查找标签位置
                Microsoft.Office.Interop.Word.Table table = app.Selection.Tables.Add(range, dt.Table.Rows.Count + 1, 10, ref oMissing, ref oMissing);

                //设置表格的字体大小粗细
                table.Range.Font.Size = 10;
                table.Range.Font.Bold = 0;

                //设置表格标题
                int rowIndex = 1;
                table.Cell(rowIndex, 1).Range.Text  = "序号";
                table.Cell(rowIndex, 2).Range.Text  = "备案号(VIN)";
                table.Cell(rowIndex, 3).Range.Text  = "产品型号";
                table.Cell(rowIndex, 4).Range.Text  = "通用名称";
                table.Cell(rowIndex, 5).Range.Text  = "燃料种类";
                table.Cell(rowIndex, 6).Range.Text  = "燃料消耗量(综合)";
                table.Cell(rowIndex, 7).Range.Text  = "整备质量";
                table.Cell(rowIndex, 8).Range.Text  = "变速器型式";
                table.Cell(rowIndex, 9).Range.Text  = "座椅排数";
                table.Cell(rowIndex, 10).Range.Text = "操作类型";


                //循环数据创建数据行

                foreach (DataRow r in dt.Table.Rows)
                {
                    rowIndex++;
                    table.Cell(rowIndex, 1).Range.Text = (rowIndex - 1).ToString();
                    for (int i = 2; i < 10; i++)
                    {
                        table.Cell(rowIndex, i).Range.Text = Convert.ToString(r[i - 1]);
                    }
                    table.Cell(rowIndex, 10).Range.Text = Convert.ToString(r["APPLYTYPE"]);
                }

                //为表格划线
                range.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle        = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle       = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle      = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle     = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle   = WdLineStyle.wdLineStyleSingle;


                //对替换好的word模板另存为一个新的word文档
                doc.SaveAs(saveFileName,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

                //准备导出word
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭word文档
                }
                if (app != null)
                {
                    app.Quit();//退出word应用程序
                }
            }
        }
Ejemplo n.º 23
0
    //按隶属分类时插入汇总表
    private void InsertSummaryTable(Microsoft.Office.Interop.Word.Document wordDoc, Microsoft.Office.Interop.Word.Application wordApp)
    {
        //设置布局方向
        wordApp.Selection.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;
        wordApp.Selection.PageSetup.TopMargin = wordApp.CentimetersToPoints(2.54F);
        wordApp.Selection.PageSetup.BottomMargin = wordApp.CentimetersToPoints(2.54F);
        wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(3.18F);
        wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(3.18F);

        //中央各部门
        wordDoc.Paragraphs.First.Range.Select();
        //wordApp.Selection.TypeParagraph();
        wordApp.Selection.Font.Size = 15F;
        wordApp.Selection.Font.Bold = 2;
        wordApp.Selection.TypeText("中央级各部门大型科学仪器数量汇总表");
        wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
  
        wordApp.Selection.TypeParagraph();
        wordApp.Selection.TypeParagraph();

        Microsoft.Office.Interop.Word.Table newTable = wordDoc.Tables.Add(wordApp.Selection.Range, centralDepartmentNames.Count + 2,
                3, ref Nothing, ref Nothing);

        //设置表格样式
        newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
        newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
        newTable.Range.Font.Size = 12F;
        newTable.Range.Font.Bold = 0;
        newTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;


        //设置表格列宽
        float sumWidth = newTable.Columns[1].Width * 3;
        newTable.Columns[1].Width = 60f;
        newTable.Columns[3].Width = 60f;
        newTable.Columns[2].Width = sumWidth - 120;

        //设置行高
        newTable.Rows.Height = 17f;
        newTable.Rows.HeightRule = WdRowHeightRule.wdRowHeightExactly; //固定行高

        Range range = newTable.Rows[1].Range;

        range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlack;
        range.Font.Bold = 1;
        range.Font.Size = 11f;
        range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        range.Cells[1].Range.Text = "序号";
        range.Cells[2].Range.Text = "中央级部门";
        range.Cells[3].Range.Text = "数量";

        int i = 1;
        int sum = 0;
        foreach (string name in centralDepartmentSorted)
        {
            if (centralDepartmentNames.ContainsKey(name))
            {
                range = newTable.Rows[i + 1].Range;
                range.Font.Size = 11f;
                range.Cells[1].Range.Text = i.ToString();
                range.Cells[1].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                range.Cells[2].Range.Text = name;
                range.Cells[2].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                range.Cells[1].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                range.Cells[3].Range.Text = centralDepartmentNames[name].ToString();
                range.Cells[1].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                sum += centralDepartmentNames[name];
                i++;
            }
        }
        i++;
        newTable.Rows[i].Range.Cells[1].Range.Text = "总计";
        newTable.Rows[i].Range.Cells[1].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
        newTable.Cell(i, 3).Range.Text = sum.ToString();
        newTable.Cell(i, 3).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
        newTable.Cell(i, 3).Range.Font.Size = 12;
        newTable.Cell(i, 1).Range.Font.Bold = 3;
        newTable.Cell(i, 1).Range.Font.Size = 12;
        newTable.Cell(i, 3).Range.Font.Bold = 3;

        object count = newTable.Rows.Count;
        object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//按行移动
        wordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点

        //插入分页符
        object oPageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdSectionBreakNextPage;
        wordApp.Application.Selection.InsertBreak(oPageBreak);

        wordApp.ActiveDocument.Paragraphs.Last.Range.Select();
        wordApp.Selection.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;

        //地方各省市
        wordApp.Selection.TypeText("地方各省市大型科学仪器数量汇总表");
        wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
        wordApp.Selection.Font.Size = 15F;
        wordApp.Selection.Font.Bold = 2;
        wordApp.Selection.TypeParagraph();
        wordApp.Selection.TypeParagraph();

        newTable = wordDoc.Tables.Add(wordApp.Selection.Range, localProvinceNames.Count + 2,
                3, ref Nothing, ref Nothing);

        //设置表格样式
        newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
        newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
        newTable.Range.Font.Size = 11f;
        newTable.Range.Font.Bold = 0;

        //设置表格列宽
        newTable.Columns[1].Width = 60f;
        newTable.Columns[3].Width = 60f;
        newTable.Columns[2].Width = sumWidth - 120;

        //设置行高
        newTable.Rows.Height = 17f;
        newTable.Rows.HeightRule = WdRowHeightRule.wdRowHeightExactly; //固定行高

        range = newTable.Rows[1].Range;

        range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlack;
        range.Font.Bold = 1;
        range.Font.Size = 11f;
        range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        range.Cells[1].Range.Text = "序号";
        range.Cells[2].Range.Text = "地方各省份";
        range.Cells[3].Range.Text = "数量";

        i = 1;
        sum = 0;
        foreach (string name in SharedData.areaListSorted)
        {
            if (localProvinceNames.ContainsKey(name))
            {
                range = newTable.Rows[i + 1].Range;
                range.Font.Size = 11f;
                range.Cells[1].Range.Text = i.ToString();
                range.Cells[1].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                range.Cells[2].Range.Text = name;
                range.Cells[2].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                range.Cells[3].Range.Text = localProvinceNames[name].ToString();
                range.Cells[3].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                sum += localProvinceNames[name];
                i++;
            }
        }
        i++;
        newTable.Rows[i].Range.Cells[1].Range.Text = "总计";
        newTable.Rows[i].Range.Cells[1].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
        newTable.Cell(i, 3).Range.Text = sum.ToString();
        newTable.Cell(i, 3).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
        newTable.Cell(i, 3).Range.Font.Size = 12;
        newTable.Cell(i, 1).Range.Font.Bold = 3;
        newTable.Cell(i, 1).Range.Font.Size = 12;
        newTable.Cell(i, 3).Range.Font.Bold = 3;

        wordApp.Selection.TypeParagraph();
        wordApp.ActiveDocument.Paragraphs.Last.Range.Select();

        //插入分页符
        oPageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdSectionBreakNextPage;
        wordApp.Application.Selection.InsertBreak(oPageBreak);

        Log.RecordLog(@"汇总表生成成功! ");
    }
Ejemplo n.º 24
0
        // 给表格添加一行
        public void AddRow(Microsoft.Office.Interop.Word.Table table)
        {
            object miss = System.Reflection.Missing.Value;

            table.Rows.Add(ref miss);
        }
Ejemplo n.º 25
0
        public void GetNewReport(DataTable dt)
        {
            object oMissing = System.Reflection.Missing.Value;
            object unknow   = Type.Missing;
            object start    = 0;
            object end      = 0;

            Microsoft.Office.Interop.Word.Range tableLocation = ActiveDocumentManager.getDefaultAD().Range(ref start, ref end);
            // 添加页眉
            emrTaskPane.wordApp.ActiveWindow.View.Type     = Word.WdViewType.wdOutlineView;
            emrTaskPane.wordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader;
            emrTaskPane.wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("");
            emrTaskPane.wordApp.Selection.ParagraphFormat.Alignment   = Word.WdParagraphAlignment.wdAlignParagraphRight; //设置右对齐
            emrTaskPane.wordApp.ActiveWindow.View.SeekView            = Word.WdSeekView.wdSeekMainDocument;              //跳出页眉设置
            emrTaskPane.wordApp.Selection.ParagraphFormat.LineSpacing = 15f;                                             //设置文档的行间距
            //移动焦点并换行
            object count  = 14;
            object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;              //换一行;

            emrTaskPane.wordApp.Selection.MoveDown(ref WdLine, ref count, ref unknow); //移动焦点
            emrTaskPane.wordApp.Selection.MoveDown(ref WdLine, ref count, ref unknow); //移动焦点
            emrTaskPane.wordApp.Selection.TypeParagraph();                             //插入段落

            Word.Range range = ActiveDocumentManager.getDefaultAD().Paragraphs.Last.Range;
            range.Start = ActiveDocumentManager.getDefaultAD().Paragraphs.Last.Range.End;
            range.Select();
            ///range.Text = "终末病历质量评分汇总表" + "(" + comboBox2.Text + "年" + comboBox1.Text + "月)";
            range.Text = "终末病历质量评分汇总表";
            range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            range.Font.Name = "黑体";
            range.Font.Size = 14.5f;
            range.Start     = range.End;
            range.Select();
            Microsoft.Office.Interop.Word.Table newTable = ActiveDocumentManager.getDefaultAD().Tables.Add(emrTaskPane.wordApp.Selection.Range, dt.Rows.Count + 1, 8, ref unknow, ref unknow);

            //设置表格样式
            newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            newTable.Borders.InsideLineStyle  = Word.WdLineStyle.wdLineStyleSingle;
            emrTaskPane.wordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距
            newTable.Cell(1, 1).Range.Text = "出院日期";
            newTable.Cell(1, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newTable.Cell(1, 2).Range.Text = "科室";
            newTable.Cell(1, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newTable.Cell(1, 3).Range.Text = "主管医师";
            newTable.Cell(1, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newTable.Cell(1, 4).Range.Text = "病案号";
            newTable.Cell(1, 4).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newTable.Cell(1, 5).Range.Text = "扣分原因";
            newTable.Cell(1, 5).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newTable.Cell(1, 6).Range.Text = "扣分";
            newTable.Cell(1, 6).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newTable.Cell(1, 7).Range.Text = "得分";
            newTable.Cell(1, 7).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newTable.Cell(1, 8).Range.Text = "病历级别";
            newTable.Cell(1, 8).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newTable.Columns[1].Width = 40f;
            newTable.Columns[2].Width = 36f;
            newTable.Columns[3].Width = 45f;//能显示三个字
            newTable.Columns[4].Width = 43f;
            newTable.Columns[5].Width = 150f;
            newTable.Columns[6].Width = 40f;
            newTable.Columns[7].Width = 40f;
            newTable.Columns[8].Width = 36f;
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    newTable.Cell(i + 2, 1).Range.Text = dt.Rows[i]["出院日期"].ToString();
                    newTable.Cell(i + 2, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    newTable.Cell(i + 2, 2).Range.Text = dt.Rows[i]["科室"].ToString();
                    newTable.Cell(i + 2, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    newTable.Cell(i + 2, 3).Range.Text = dt.Rows[i]["主管医师"].ToString();
                    newTable.Cell(i + 2, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    newTable.Cell(i + 2, 4).Range.Text = dt.Rows[i]["病案号"].ToString();
                    newTable.Cell(i + 2, 4).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    newTable.Cell(i + 2, 5).Range.Text = dt.Rows[i]["扣分原因"].ToString();
                    newTable.Cell(i + 2, 5).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    newTable.Cell(i + 2, 6).Range.Text = dt.Rows[i]["扣分"].ToString();
                    newTable.Cell(i + 2, 6).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    newTable.Cell(i + 2, 7).Range.Text = dt.Rows[i]["得分"].ToString();
                    newTable.Cell(i + 2, 7).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    newTable.Cell(i + 2, 8).Range.Text = dt.Rows[i]["病历级别"].ToString();
                    newTable.Cell(i + 2, 8).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                }
            }
            object Line1 = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;

            //object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;
            emrTaskPane.wordApp.Selection.MoveDown(ref Line1, ref count, ref unknow); //移动焦点
            emrTaskPane.wordApp.Selection.MoveDown(ref Line1, ref count, ref unknow); //移动焦点
            emrTaskPane.wordApp.Selection.TypeParagraph();                            //插入段落
            Word.Range range1 = ActiveDocumentManager.getDefaultAD().Paragraphs.Last.Range;
            range1.Start = ActiveDocumentManager.getDefaultAD().Paragraphs.Last.Range.End;
            range1.Select();
            range1.Text = "记录数共计" + dt.Rows.Count.ToString() + "条";
            range1.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
            range1.Font.Name = "黑体";
            range1.Font.Size = 10f;
            range1.Start     = range.End;
            //Globals.ThisAddIn.ShowNoteMenu();
            //Globals.ThisAddIn.noteMenu.OperationEnableForStat(true);
        }
Ejemplo n.º 26
0
 // 删除表格第rows行,n为表格的序号
 public void DeleteRow(int n, int row)
 {
     Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
     table.Rows[row].Delete();
 }
Ejemplo n.º 27
0
 // 给表格中单元格插入元素,table所在表格,row行号,column列号,value插入的元素
 public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value)
 {
     table.Cell(row, column).Range.Text = value;
 }