C\#Word 파일 생 성(그림,텍스트)
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;
}
}
//
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);
// wordDoc,wordApp
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)
{
//
wordDoc.Content.InsertAfter(strContent);
wordApp.Selection.EndKey(ref unite, ref Nothing); //
}
public void InsertTitle(string strContent)
{
//
wordApp.Selection.EndKey(ref unite, ref Nothing); //
try
{
wordDoc.Paragraphs.Last.Range.set_Style(" 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); //
try
{
wordDoc.Paragraphs.Last.Range.set_Style("Normal");
}
catch (Exception ex)
{
wordDoc.Paragraphs.Last.Range.set_Style(" ");
}
}
//
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
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);
//
newTable.Borders.Enable = 1; // , ( 0 ,1 ,2、3 , )
newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//
if (width != 0)
{
newTable.PreferredWidth = width;//
}
newTable.AllowPageBreaks = false;
return newTable;
}
// id, , , ,
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));
}
// , , , ,
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));
}
// Align ,Vertical ( , , 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;//
case 0: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//
case 1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//
}
switch (Vertical)
{
case -1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//
case 0: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//
case 1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//
}
}
//
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;//
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;//
}
switch (Vertical)
{
case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//
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;//
}
}
//
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;
}
}
//
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 ,use
// int bool
//
public void UseBorder(int n, bool use)
{
if (use)
{
wordDoc.Content.Tables[n].Borders.Enable = 1;
// , ( 0 ,1 ,2、3 , )
}
else
{
wordDoc.Content.Tables[n].Borders.Enable = 0;
}
}
// ,n 1
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
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
public void DeleteRow(int n, int row)
{
Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
table.Rows[row].Delete();
}
// ,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;
}
// ,n 1 ,row ,column ,value
public void InsertCell(int n, int row, int column, string value)
{
wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value;
}
// ,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];
}
}
//
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; //
wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight; //
}
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); //
// Word
Object range = wordDoc.Paragraphs.Last.Range;
//
Object linkToFile = false; // , bool
// Word
Object saveWithDocument = true; //
// InlineShapes.AddPicture (【 “ ”】)
InlineShape shape = wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
wordApp.Selection.ParagraphFormat.Alignment = align;//
//
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;//
}
// ,text
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 = "
";
}
// winword.exe
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); //
MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range,
tableRow, tableColumn, ref Nothing, ref Nothing);
// , ,
table.Borders.Enable = 0;// , 5、13
// 1 。
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));//
}
}
}
// table
table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;// : ?
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;//
// table
table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//
table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//
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(); //
report.InsertTitle(" ");
float width = 420;//
float height = 200;//
report.InsertPicture(" ", width, height, WdParagraphAlignment.wdAlignParagraphCenter);
report.SaveDocument(path+ fileName);
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebView2를 Visual Studio 2017 Express에서 사용할 수 있을 때까지Evergreen .Net Framework SDK 4.8 VisualStudio2017에서 NuGet을 사용하기 때문에 패키지 관리 방법을 packages.config 대신 PackageReference를 사용해야...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.