亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#生成Word文件(圖片、文字)

 更新時(shí)間:2019年05月29日 15:34:12   作者:Daniel799  
這篇文章主要為大家詳細(xì)介紹了C#生成Word文件,包括圖片、文字等素材,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了C#生成Word文件的具體代碼,供大家參考,具體內(nèi)容如下

通過(guò)Microsoft.Office.Interop.Word生成Word文檔

1.引用類 WordReport.cs,代碼如下:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Word;
using MSWord = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.IO;
 
namespace CRM.Common
{
  public class WordReport
  {
    private _Application wordApp = null;
    private _Document wordDoc = null;
    object unite = MSWord.WdUnits.wdStory;
    Object Nothing = Missing.Value;
    public _Application Application
    {
      get
      {
        return wordApp;
      }
      set
      {
        wordApp = value;
      }
    }
    public _Document Document
    {
      get
      {
        return wordDoc;
      }
      set
      {
        wordDoc = value;
      }
    }
 
    // 通過(guò)模板創(chuàng)建新文檔
    public void CreateNewDocument(string filePath)
    {
      try
      {
        killWinWordProcess();
        wordApp = new ApplicationClass();
        wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
        wordApp.Visible = false;
        object missing = System.Reflection.Missing.Value;
        object templateName = filePath;
        wordDoc = wordApp.Documents.Open(ref templateName, 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);
      }
      catch (Exception ex)
      {
        
      }
    }
    public void CreateNewDocument()
    {
      try
      {
        //killWinWordProcess();
        wordApp = new ApplicationClass();
        wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
        wordApp.Visible = false;
        Object Nothing = Missing.Value;
        wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
      }
      catch (Exception ex)
      {
        
      }
    }
    // 保存新文件
    public void SaveDocument(string filePath)
    {
      if (File.Exists((string)filePath))
      {
        File.Delete((string)filePath);
      }
      object fileName = filePath;
      object format = WdSaveFormat.wdFormatDocument;//保存格式
      object miss = System.Reflection.Missing.Value;
      wordDoc.SaveAs(ref fileName, ref format, ref miss,
        ref miss, ref miss, ref miss, ref miss,
        ref miss, ref miss, ref miss, ref miss,
        ref miss, ref miss, ref miss, ref miss,
        ref miss);
      //關(guān)閉wordDoc,wordApp對(duì)象
      object SaveChanges = WdSaveOptions.wdSaveChanges;
      object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
      object RouteDocument = false;
      wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
      wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
    }
    public void InsertText(string strContent)
    {
      //寫(xiě)入普通文本
      wordDoc.Content.InsertAfter(strContent);
      wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標(biāo)移動(dòng)到文檔末尾
 
      
    }
    public void InsertTitle(string strContent)
    {
      //寫(xiě)入普通文本
      wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標(biāo)移動(dòng)到文檔末尾
 
      try
      {
        wordDoc.Paragraphs.Last.Range.set_Style("標(biāo)題 5");
      }
      catch (Exception ex)
      {
        wordDoc.Paragraphs.Last.Range.set_Style("Heading 5");
      }
      wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlack;
      wordDoc.Paragraphs.Last.Range.Font.Size = 11;
      wordDoc.Paragraphs.Last.Range.Font.Name = "宋體";
      wordDoc.Paragraphs.Last.Range.Text = strContent;
      wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標(biāo)移動(dòng)到文檔末尾
      try
      {
        wordDoc.Paragraphs.Last.Range.set_Style("Normal");
      }
      catch (Exception ex)
      {
        wordDoc.Paragraphs.Last.Range.set_Style("正文");
      }
 
 
    }
    // 在書(shū)簽處插入值
    public bool InsertValue(string bookmark, string value)
    {
      object bkObj = bookmark;
      if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark))
      {
        wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
        wordApp.Selection.TypeText(value);
        return true;
      }
      return false;
    }
 
    // 插入表格,bookmark書(shū)簽
    public Table InsertTable(string bookmark, int rows, int columns, float width)
    {
      object miss = System.Reflection.Missing.Value;
      object oStart = bookmark;
      Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置
      Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss);
      //設(shè)置表的格式
      newTable.Borders.Enable = 1; //允許有邊框,默認(rèn)沒(méi)有邊框(為0時(shí)報(bào)錯(cuò),1為實(shí)線邊框,2、3為虛線邊框,以后的數(shù)字沒(méi)試過(guò))
      newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//邊框?qū)挾?
      if (width != 0)
      {
        newTable.PreferredWidth = width;//表格寬度
      }
      newTable.AllowPageBreaks = false;
      return newTable;
    }
 
 
    // 合并單元格 表id,開(kāi)始行號(hào),開(kāi)始列號(hào),結(jié)束行號(hào),結(jié)束列號(hào)
    public void MergeCell(int n, int row1, int column1, int row2, int column2)
    {
      wordDoc.Content.Tables[n].Cell(row1, column1).Merge(wordDoc.Content.Tables[n].Cell(row2, column2));
    }
 
    // 合并單元格 表名,開(kāi)始行號(hào),開(kāi)始列號(hào),結(jié)束行號(hào),結(jié)束列號(hào)
    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));
    }
 
    // 設(shè)置表格內(nèi)容對(duì)齊方式 Align水平方向,Vertical垂直方向(左對(duì)齊,居中對(duì)齊,右對(duì)齊分別對(duì)應(yīng)Align和Vertical的值為-1,0,1)Microsoft.Office.Interop.Word.Table table
    public void SetParagraph_Table(int n, int Align, int Vertical)
    {
      switch (Align)
      {
        case -1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左對(duì)齊
        case 0: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中
        case 1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右對(duì)齊
      }
      switch (Vertical)
      {
        case -1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//頂端對(duì)齊
        case 0: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中
        case 1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端對(duì)齊
      }
    }
 
    // 設(shè)置單元格內(nèi)容對(duì)齊方式
    public void SetParagraph_Table(int n, int row, int column, int Align, int Vertical)
    {
      switch (Align)
      {
        case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左對(duì)齊
        case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中
        case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右對(duì)齊
      }
      switch (Vertical)
      {
        case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//頂端對(duì)齊
        case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中
        case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端對(duì)齊
      }
 
    }
 
 
    // 設(shè)置表格字體
    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;
      }
    }
 
    // 設(shè)置單元格字體
    public void SetFont_Table(int n, int row, int column, string fontName, double size, int bold)
    {
      if (size != 0)
      {
        wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Size = Convert.ToSingle(size);
      }
      if (fontName != "")
      {
        wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Name = fontName;
      }
      wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Bold = bold;// 0 表示不是粗體,其他值都是
    }
 
    // 是否使用邊框,n表格的序號(hào),use是或否
    // 該處邊框參數(shù)可以用int代替bool可以讓方法更全面
    // 具體值方法中介紹
    public void UseBorder(int n, bool use)
    {
      if (use)
      {
        wordDoc.Content.Tables[n].Borders.Enable = 1;
        //允許有邊框,默認(rèn)沒(méi)有邊框(為0時(shí)無(wú)邊框,1為實(shí)線邊框,2、3為虛線邊框,以后的數(shù)字沒(méi)試過(guò))
      }
      else
      {
        wordDoc.Content.Tables[n].Borders.Enable = 0;
      }
    }
 
    // 給表格插入一行,n表格的序號(hào)從1開(kāi)始記
    public void AddRow(int n)
    {
      object miss = System.Reflection.Missing.Value;
      wordDoc.Content.Tables[n].Rows.Add(ref miss);
    }
 
    // 給表格添加一行
    public void AddRow(Microsoft.Office.Interop.Word.Table table)
    {
      object miss = System.Reflection.Missing.Value;
      table.Rows.Add(ref miss);
    }
 
    // 給表格插入rows行,n為表格的序號(hào)
    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);
      }
    }
 
    // 刪除表格第rows行,n為表格的序號(hào)
    public void DeleteRow(int n, int row)
    {
      Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
      table.Rows[row].Delete();
    }
 
    // 給表格中單元格插入元素,table所在表格,row行號(hào),column列號(hào),value插入的元素
    public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value)
    {
      table.Cell(row, column).Range.Text = value;
    }
 
    // 給表格中單元格插入元素,n表格的序號(hào)從1開(kāi)始記,row行號(hào),column列號(hào),value插入的元素
    public void InsertCell(int n, int row, int column, string value)
    {
      wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value;
    }
 
    // 給表格插入一行數(shù)據(jù),n為表格的序號(hào),row行號(hào),columns列數(shù),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];
      }
    }
 
    // 插入圖片
    public void InsertPicture(string bookmark, string picturePath, float width, float hight)
    {
      object miss = System.Reflection.Missing.Value;
      object oStart = bookmark;
      Object linkToFile = false;    //圖片是否為外部鏈接
      Object saveWithDocument = true; //圖片是否隨文檔一起保存 
      object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//圖片插入位置
      wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
      wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width;  //設(shè)置圖片寬度
      wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight; //設(shè)置圖片高度
    }
    public void InsertPicture(string picturePath, float width, float hight,WdParagraphAlignment align)
    {
      object unite = MSWord.WdUnits.wdStory;
      Object Nothing = Missing.Value;
      Application.Selection.EndKey(ref unite, ref Nothing); //將光標(biāo)移動(dòng)到文檔末尾
      //要向Word文檔中插入圖片的位置
      Object range = wordDoc.Paragraphs.Last.Range;
      //定義該插入的圖片是否為外部鏈接
      Object linkToFile = false;        //默認(rèn),這里貌似設(shè)置為bool類型更清晰一些
      //定義要插入的圖片是否隨Word文檔一起保存
      Object saveWithDocument = true;       //默認(rèn)
      //使用InlineShapes.AddPicture方法(【即“嵌入型”】)插入圖片
      InlineShape shape = wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
      wordApp.Selection.ParagraphFormat.Alignment = align;//
      
      //設(shè)置圖片寬高的絕對(duì)大小
      if (width!=-1)
        wordDoc.InlineShapes[1].Width = width;
      if(hight!=-1)
        wordDoc.InlineShapes[1].Height = hight;
      try
      {
        wordDoc.Paragraphs.Last.Range.set_Style("正文");
      }
      catch(Exception ex)
      {
        wordDoc.Paragraphs.Last.Range.set_Style("Normal");
      }   
      shape.Borders.Enable = 12;
    
      //shape.ConvertToShape().WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;//四周環(huán)繞的方式
    }
 
    // 插入一段文字,text為文字內(nèi)容
    public void InsertText(string bookmark, string text)
    {
      object oStart = bookmark;
      object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;
      Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range);
      wp.Format.SpaceBefore = 6;
      wp.Range.Text = text;
      wp.Format.SpaceAfter = 24;
      wp.Range.InsertParagraphAfter();
      wordDoc.Paragraphs.Last.Range.Text = "\n";
    }
 
    // 殺掉winword.exe進(jìn)程
    public void killWinWordProcess()
    {
      System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
      foreach (System.Diagnostics.Process process in processes)
      {
        bool b = process.MainWindowTitle == "";
        if (process.MainWindowTitle == "")
        {
          process.Kill();
        }
      }
    }
 
 
 
    internal void InsertTable(int tableRow, int tableColumn,List<string> imagePaths)
    {
      wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標(biāo)移動(dòng)到文檔末尾
      MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range,
                          tableRow, tableColumn, ref Nothing, ref Nothing);
 
      //默認(rèn)創(chuàng)建的表格沒(méi)有邊框,這里修改其屬性,使得創(chuàng)建的表格帶有邊框 
      table.Borders.Enable = 0;//這個(gè)值可以設(shè)置得很大,例如5、13等等
 
      //表格的索引是從1開(kāi)始的。
      for (int i = 1; i <= tableRow; i++)
      {
        for (int j = 1; j <= tableColumn; j++)
        {
          
          int index = (i-1) * tableColumn + j-1;
          if (index < imagePaths.Count)//有文件
          {
            string FileName = imagePaths[index]; //圖片所在路徑
            object LinkToFile = false;
            object SaveWithDocument = true;
            object Anchor = table.Cell(i, j).Range;//選中要添加圖片的單元格
            MSWord.InlineShape il = wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
 
            //圖片大小
            il.Width = 100;//圖片寬度
            il.Height = 100;//圖片高度
            table.Rows[i].Cells[j].Split(2, 1);
            table.Cell(i+1, j).Range.Text = "圖片名稱:"+(index+1).ToString(); //
            table.Cell(i+1, j).Merge(table.Cell(i, j));//縱向合并
          }
        }
      }
      //設(shè)置table樣式
      table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;//高度規(guī)則是:行高有最低值下限?
      table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));// 
 
      table.Range.Font.Size = 10.5F;
      table.Range.Font.Bold = 0;
 
      table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//表格文本居中
      table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;//文本垂直貼到底部
      //設(shè)置table邊框樣式
      table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//表格外框是雙線
      table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//表格內(nèi)框是單線
 
      table.Rows[1].Range.Font.Bold = 1;//加粗
      table.Rows[1].Range.Font.Size = 12F;
      table.Cell(1, 1).Range.Font.Size = 10.5F;
    }
  }
}

2.生成Word文檔

/// <summary>
/// 
/// </summary>
/// <param name="path">like string path=@"c:\\temp\\"</param>
public void GengerateWord(string path)
    {
      string fileName = "test.doc";
      WordReport report = new WordReport();
      report.CreateNewDocument(); //創(chuàng)建文件
      report.InsertTitle("標(biāo)題");
      float width = 420;//圖片寬度
      float height = 200;//圖片高度
      report.InsertPicture("圖片地址", width, height, WdParagraphAlignment.wdAlignParagraphCenter);
      report.SaveDocument(path+ fileName);
}


 以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • C#判斷當(dāng)前程序是否通過(guò)管理員運(yùn)行的方法

    C#判斷當(dāng)前程序是否通過(guò)管理員運(yùn)行的方法

    這篇文章主要介紹了C#判斷當(dāng)前程序是否通過(guò)管理員運(yùn)行的方法,可通過(guò)非常簡(jiǎn)單的系統(tǒng)函數(shù)調(diào)用實(shí)現(xiàn)對(duì)當(dāng)前程序是否通過(guò)管理員運(yùn)行進(jìn)行判定,是非常實(shí)用的技巧,需要的朋友可以參考下
    2014-11-11
  • C#集合本質(zhì)之隊(duì)列的用法詳解

    C#集合本質(zhì)之隊(duì)列的用法詳解

    本文詳細(xì)講解了C#集合本質(zhì)之隊(duì)列的用法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-08-08
  • 淺談C#2.0泛型中的變化:default關(guān)鍵字

    淺談C#2.0泛型中的變化:default關(guān)鍵字

    下面就詳細(xì)的說(shuō)明一下。之所以會(huì)用到default關(guān)鍵字,是因?yàn)樾枰诓恢李愋蛥?shù)為值類型還是引用類型的情況下,為對(duì)象實(shí)例賦初值
    2013-09-09
  • 區(qū)分WCF與WebService的異同、優(yōu)勢(shì)

    區(qū)分WCF與WebService的異同、優(yōu)勢(shì)

    這篇文章主要幫助大家區(qū)分WCF與WebService的異同、優(yōu)勢(shì),分為三大方面進(jìn)行研究學(xué)習(xí),感興趣的小伙伴們可以參考一下
    2016-03-03
  • C#執(zhí)行Javascript代碼的幾種方法總結(jié)

    C#執(zhí)行Javascript代碼的幾種方法總結(jié)

    本篇文章主要是對(duì)C#執(zhí)行Javascript代碼的幾種方法進(jìn)行了詳細(xì)的總結(jié)介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助
    2014-01-01
  • C#定義簡(jiǎn)單的反射工廠實(shí)例分析

    C#定義簡(jiǎn)單的反射工廠實(shí)例分析

    這篇文章主要介紹了C#定義簡(jiǎn)單的反射工廠的用法,實(shí)例分析了反射工廠的原理與使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-04-04
  • C#實(shí)現(xiàn)懸浮窗口的方法詳解

    C#實(shí)現(xiàn)懸浮窗口的方法詳解

    這篇文章主要為大家詳細(xì)介紹了C#如何實(shí)現(xiàn)懸浮窗口的相關(guān)資料,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以了解一下
    2022-12-12
  • C#實(shí)現(xiàn)簡(jiǎn)單打字小游戲

    C#實(shí)現(xiàn)簡(jiǎn)單打字小游戲

    這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)簡(jiǎn)單打字小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-05-05
  • C#高性能動(dòng)態(tài)獲取對(duì)象屬性值的步驟

    C#高性能動(dòng)態(tài)獲取對(duì)象屬性值的步驟

    這篇文章主要介紹了C#高性能動(dòng)態(tài)獲取對(duì)象屬性值的步驟,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下
    2020-12-12
  • C#實(shí)現(xiàn)讀取多條數(shù)據(jù)記錄并導(dǎo)出到Word

    C#實(shí)現(xiàn)讀取多條數(shù)據(jù)記錄并導(dǎo)出到Word

    這篇文章主要為大家詳細(xì)介紹了C#如何實(shí)現(xiàn)讀取多條數(shù)據(jù)記錄并導(dǎo)出到Word,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-03-03

最新評(píng)論