Created
February 27, 2018 08:58
-
-
Save immengineer/31485a42df3349eebc936b920bcd836b to your computer and use it in GitHub Desktop.
Excel 画像ファイル貼付
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace sample | |
{ | |
class Excel | |
{ | |
dynamic excelApp = null; | |
dynamic workBooks = null; | |
dynamic workBook = null; | |
dynamic workSheets = null; | |
dynamic workSheet = null; | |
dynamic range = null; | |
dynamic shape = null; | |
/// <summary> | |
/// Excelファイルを新規作成 | |
/// </summary> | |
/// <param name="excelfile">保存するExcelファイル名(フルパス)</param> | |
/// <param name="imagefile">貼り付ける画像ファイル名(フルパス)</param> | |
public void MakeExcelFile(string excelfile, string imagefile) | |
{ | |
try | |
{ | |
Type excelApplication = Type.GetTypeFromProgID("Excel.Application"); | |
excelApp = Activator.CreateInstance(excelApplication); | |
// 確認メッセージ非表示 | |
excelApp.DisplayAlerts = false; | |
// ワークブック、シート定義 | |
workBooks = excelApp.WorkBooks; | |
workBook = workBooks.Add(); | |
workSheets = workBook.Sheets; | |
workSheet = workSheets["Sheet1"]; | |
// セルA2選択 | |
range = workSheet.Range["A2"]; | |
// 画像貼付 | |
double Left = range.Left; | |
double Top = range.Top; | |
double Width = 0; | |
double Height = 0; | |
shape = workSheet.Shapes.AddPicture(imagefile, true, true, Left, Top, Width, Height); | |
// 倍率を100%にする | |
shape.ScaleHeight(1.0, true); | |
shape.ScaleWidth(1.0, true); | |
// Bookを別名で保存し、アプリ終了 | |
workBook.SaveAs(excelfile); | |
workBook.Close(); | |
excelApp.Quit(); | |
} | |
finally | |
{ | |
releaseObject((object)shape); | |
releaseObject((object)range); | |
releaseObject((object)workSheet); | |
releaseObject((object)workSheets); | |
releaseObject((object)workBook); | |
releaseObject((object)workBooks); | |
releaseObject((object)excelApp); | |
} | |
} | |
/// <summary> | |
/// Excelオブジェクトリリース用 | |
/// </summary> | |
/// <param name="obj">リリースするオブジェクト</param> | |
private void releaseObject(object obj) | |
{ | |
try | |
{ | |
Marshal.FinalReleaseComObject(obj); | |
obj = null; | |
} | |
catch (Exception e) | |
{ | |
obj = null; | |
MessageBox.Show("Can't Release Object " + e.ToString()); | |
} | |
finally | |
{ | |
GC.Collect(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment