假如我們導出一份履歷到word文檔,那勢必可能要同時導出我們包含的履歷,下面就來試一下如何和通過C#代碼,将圖檔插入到word文檔中。
為了簡便起見,就簡單一點。類似下面這樣的
姓名 | 張三 |
照片 | ![]() |
protected void InsertPtctureToExcel()
{
Word.Application app = null;
Word.Document doc = null;
try
{
object oMissing = System.Reflection.Missing.Value;
//圖檔位址
string fileName =Server.MapPath("photo.jpg");
object linkToFile = false;
object saveWithDocument = true;
app = new Word.Application();
doc = app.Documents.Add();
Word.Table table = doc.Tables.Add(app.Selection.Range, 2, 2);
table.Columns[1].Width = 100f;
table.Columns[2].Width = 125f;
table.Cell(1, 1).Range.Text = "姓名";
table.Cell(1, 2).Range.Text = "張三";
table.Cell(2,1).Range.Text = "照片";
table.Cell(2, 2).Select();
object range = app.Selection.Range;
Word.InlineShape shape = app.ActiveDocument.InlineShapes.AddPicture(fileName, ref linkToFile, ref saveWithDocument, ref range);
shape.Width = 100f;//圖檔寬度
shape.Height = 120f;//圖檔高度
shape.ConvertToShape().WrapFormat.Type = Word.WdWrapType.wdWrapSquare;//四周環繞的方式
string newFile = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc";
string physicNewFile = Server.MapPath(newFile);
doc.SaveAs(physicNewFile);
}
catch (Exception ex)
{
}
finally
{
if (doc != null)
{
doc.Close();//關閉文檔
}
if (app != null)
{
app.Quit();//退出應用程式
}
}
}