zoukankan      html  css  js  c++  java
  • 使用Interop.Excel生成Word表格文档

       /// <summary>
            /// 创建Word文档
            /// </summary>
            /// <param name="ds">ds中每个datatable在word中生成一个表格</param>
            /// <returns></returns>
            public static string CreateWord(DataSet ds)
            {
                string msg = string.Empty;

                Object Nothing = System.Reflection.Missing.Value;
                //创建Word文档
                Word.Application WordApp = new Word.ApplicationClass();
                WordApp.NormalTemplate.Saved = true;//避免弹出normal.dot被使用的对话框,自动保存模板(可用,非常重要)

                Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

                object filePath = @"C:\" + DateTime.Now.ToShortDateString().Replace("-", "") + DateTime.Now.ToLongTimeString().Replace(":", "") + ".doc";   //文件保存路径
                try
                {
                    int dtCount = 1;
                    foreach (DataTable dt in ds.Tables)
                    {
                        //WordDoc.Range(2, 2).InsertParagraphAfter(); //插入回车
                        WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距
                        ////移动焦点并换行
                        object count = 14;
                        object WdLine = Word.WdUnits.wdLine;//换一行;
                        WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点
                        if (dtCount != 1)
                        {
                            WordApp.Selection.TypeParagraph();//插入段落(每个表格间增加一行)
                        }

                        int rowCount = dt.Rows.Count;

                        //停留1000毫秒,否则创建表格时会报异常
                        Thread.Sleep(1000);
                        //文档中创建表格( +2表示:表名行和列头行)
                        Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, rowCount + 2, 4, ref Nothing, ref Nothing);
                        //设置表格样式
                        //newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;
                        newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
                        newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
                        newTable.Columns[1].Width = 50f;
                        newTable.Columns[2].Width = 100f;
                        newTable.Columns[3].Width = 180f;
                        newTable.Columns[4].Width = 100f;

                        #region 填充表名称
                        newTable.Cell(1, 1).Range.Text = "表名:" + dt.Rows[0]["Table_Name"].ToString();
                        newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
                        //合并单元格
                        newTable.Cell(1, 1).Merge(newTable.Cell(1, 4));
                        newTable.Cell(1, 1).Range.Font.Color = Word.WdColor.wdColorRed;//设置单元格内字体颜色
                        newTable.Cell(1, 1).Select();   //选中
                        WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
                        WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
                        #endregion

                        #region 填充列标题
                        newTable.Cell(2, 1).Range.Text = "序号";
                        newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
                        newTable.Cell(2, 2).Range.Font.Bold = 2;
                        newTable.Cell(2, 2).Range.Font.Size = 9;
                        newTable.Cell(2, 2).Select();   //选中
                        newTable.Cell(2, 2).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

                        newTable.Cell(2, 2).Range.Text = "列名";
                        newTable.Cell(2, 2).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
                        newTable.Cell(2, 2).Range.Font.Bold = 2;
                        newTable.Cell(2, 2).Range.Font.Size = 9;
                        newTable.Cell(2, 2).Select();   //选中
                        newTable.Cell(2, 2).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

                        newTable.Cell(2, 3).Range.Text = "数据类型";
                        newTable.Cell(2, 3).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
                        newTable.Cell(2, 3).Range.Font.Bold = 2;
                        newTable.Cell(2, 3).Range.Font.Size = 9;
                        newTable.Cell(2, 3).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        newTable.Cell(2, 3).Select();   //选中
                        //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

                        newTable.Cell(2, 4).Range.Text = "说明";
                        newTable.Cell(2, 4).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
                        newTable.Cell(2, 4).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        newTable.Cell(2, 4).Range.Font.Bold = 2;
                        newTable.Cell(2, 4).Range.Font.Size = 9;
                        newTable.Cell(2, 4).Select();   //选中
                        //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
                        #endregion

                        #region //填充表格内容
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            string data_Type = dt.Rows[i]["Data_Type"].ToString();                  //数据类型
                            string data_precision = dt.Rows[i]["Data_Precision"].ToString();     //精度
                            string data_length = dt.Rows[i]["Data_Length"].ToString();           //长度
                            string data_Scale = dt.Rows[i]["Data_Scale"].ToString();                //
                            string type = string.Empty;
                            if (data_precision == string.Empty) //字符串、日期等
                            {
                                if (data_Type == "DATE")
                                {
                                    type = data_Type + "()";
                                }
                                else
                                {
                                    type = data_Type + "(" + data_length + ")";
                                }
                            }
                            else //数字类型等
                            {
                                if (data_Scale == "0")
                                {
                                    type = data_Type + "(" + data_precision + ")";
                                }
                                else
                                {
                                    type = data_Type + "(" + data_precision + "," + data_Scale + ")";
                                }
                            }

                            newTable.Cell(i + 3, 1).Range.Text = Convert.ToString(i + 1);//序号
                            newTable.Cell(i + 3, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                            newTable.Cell(i + 3, 2).Range.Text = dt.Rows[i]["Column_Name"].ToString();  //列名
                            newTable.Cell(i + 3, 2).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居左

                            newTable.Cell(i + 3, 3).Range.Text = type;
                            newTable.Cell(i + 3, 3).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居左

                            newTable.Cell(i + 3, 4).Range.Text = dt.Rows[i]["Comments"].ToString();       //备注
                            newTable.Cell(i + 3, 4).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居左
                        }
                        #endregion

                        //在表格中增加行,注意不是在每个表格间增加行。这就是加了这行代码后为什么每个表格会多出空白行的原因
                        //WordDoc.Content.Tables[dtCount].Rows.Add(ref Nothing);

                        //WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
                        //WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                        //WordDoc.Content.Tables[dtCount].Rows.Add(ref Nothing);
                        dtCount++;

                        #region 插入分页(每一个表格在一页中显示)
                        //object mymissing = System.Reflection.Missing.Value;
                        //object myunit = Word.WdUnits.wdStory;
                        //WordApp.Selection.EndKey(ref myunit, ref mymissing);
                        //object pBreak = (int)Word.WdBreakType.wdPageBreak;
                        //WordApp.Selection.InsertBreak(ref pBreak);
                        #endregion
                    }


                    msg = "OK";
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                }
                finally
                {
                    //文件保存
                    WordDoc.SaveAs(ref filePath, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                    WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                    WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
                    //wordtype.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, appclass, null);//退出

                    if (WordDoc != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(WordDoc);
                        WordDoc = null;
                    }

                    if (WordApp != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
                        WordApp = null;
                    }
                    GC.Collect();
                }
                System.Diagnostics.Process.Start(filePath.ToString());

                return msg;
            }

  • 相关阅读:
    医学影像分割之HIP
    c++画分形之Julia集与Mandelbrot集
    趣题一道
    华山论剑常用角点检测与角点匹配方法比较
    改变鼠标样式
    Unity3D Pro 利用摄像头产生俯视地图效果
    unity3D小地图教程
    WebBrowser网址中特殊字符的问题
    打开多个unity3D项目 (项目多开)
    u3d按住鼠标右键才转动摄像机的方法
  • 原文地址:https://www.cnblogs.com/gossip/p/2221463.html
Copyright © 2011-2022 走看看