C# 앱에서 엑셀에 사진을 삽입하는 방법?
제 C# 어플리케이션을 이용하여 엑셀 스프레드시트에 사진을 삽입하려고 합니다.
저는 아래 내용을 출처로 사용하였습니다.http://csharp.net-informations.com/excel/csharp-insert-picture-excel.htm
이 선 전체가 파란색 밑줄이 그어져 있습니다.
xlWorkSheet.Shapes.AddPicture("C:\\pic.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45);
내 코드:
private void btnWriteSpreedSheet_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//xlWorkSheet.SetBackgroundPicture("C:/Users/Shaun/Documents/Visual Studio 2010/Projects/TestXMLToEXCEL/TestXMLToEXCEL/bin/Debugpic.JPG"); //
//add some text
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
xlWorkSheet.Cells[2, 1] = "Adding picture in Excel File";
xlWorkSheet.Shapes.AddPicture("C:\\pic.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45); //C:\\csharp-xl-picture.JPG
xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
MessageBox.Show ("File created !");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
오류 메시지:
'Microsoft'에 가장 적합한 오버로드 방식입니다.사무실.인터럽트.엑셀. 모양.그림 추가( 문자열, Microsoft).사무실.코어.MsoTriState, 마이크로소프트.사무실.Core.MsoTriState, float, float, float, float)'에 잘못된 인수가 있습니다.
'Microsoft' 유형입니다.사무실.Core.MsoTriState'는 참조되지 않는 어셈블리에 정의됩니다.어셈블리 사무실 버전=12.0.0, Culture=neutral, PublicKey에 대한 참조를 추가해야 합니다.토큰=71e9bce111e9429c'.
주장 2: 'Microsoft'에서 변환할 수 없습니다.사무실.Core.MsoTriState [c:\users\shaun\documents\visual studio 2010\Projects]테스트XMLToEXCEL\TestXMLToEXCEL\CreateSpreadSheet.cs ]에서 'Microsoft'로 테스트합니다.사무실.'Core.MsoTriState'
주장 3: 'Microsoft'에서 변환할 수 없습니다.사무실.Core.MsoTriState [c:\users\shaun\documents\visual studio 2010\Projects]테스트XMLToEXCEL\TestXMLToEXCEL\CreateSpreadSheet.cs ]에서 'Microsoft'로 테스트합니다.사무실.'Core.MsoTriState'
내 레퍼런스:
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using Microsoft.Office;
using System.Xml;
다음 참조를 추가합니다.
Microsoft.Office.Interop.Excel로부터망탭Microsoft Office 14.0 Object LibraryCOM 탭에서
문을 사용하여 다음을 추가합니다.
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
그리고 여기 방법(약간 변경)이 있습니다.
private void BtnWriteSpreedSheetClick(object sender, EventArgs e)
{
var xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add();
Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets[1];
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
xlWorkSheet.Cells[2, 1] = "Adding picture in Excel File";
xlWorkSheet.Shapes.AddPicture(@"C:\pic.JPG", MsoTriState.msoFalse, MsoTriState.msoCTrue, 50, 50, 300, 45);
xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal);
xlWorkBook.Close(true);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
MessageBox.Show("File created !");
}
마이크로소프트 엑셀 라이브러리를 추가해야 합니다.

대안으로 EPLus와 같은 Open Xml 라이브러리 중 하나를 사용하여 이 작업을 수행할 수 있습니다.
제 생각에 EPplus는 자원을 수동으로 해제할 필요 없이 엑셀 인터럽트보다 훨씬 쉽고 직관적입니다.엑셀을 설치하지 않아도 기계에서 수행할 수 있다는 부가적인 장점도 있습니다.
EPLus와 함께 이와 같이 간단한 것이 잘 작동합니다.
using (var excel = new ExcelPackage())
{
var wks = excel.Workbook.Worksheets.Add("Sheet1");
wks.Cells[1, 1].Value = "Adding picture below:";
var pic = wks.Drawings.AddPicture("MyPhoto", new FileInfo("image.png"));
pic.SetPosition(2, 0, 1, 0);
excel.SaveAs(new FileInfo("outputfile.xlsx"));
}
추가하기만 하면 됩니다.
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
다시 실행하기 전에 암호화하고 솔루션을 재구축할 수 있습니다.
저는 이 코드를 마이크로소프트와 함께 사용하고 있습니다.사무실.인터럽트.Excel v 14.0:
xlWorksheet.Shapes.AddPicture(@"c:\pics\logosmall.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 0, 0, 185, 42);
이미지가 있습니다(jpg그리고.png내 엑셀 시트에.
private void Button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application application = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = application.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.FileName = "ImageToExcel.xlsx";
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "Image to Excel";
string imageNetworkLocation = "\\\\192.168.240.110\\images\\image.png";
worksheet.Shapes.AddPicture(imageNetworkLocation, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 0, 0, 170, 85);
workbook.SaveAs(saveDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
application.Quit();
workbook = null;
application = null;
}
}
else
try
{
workbook.Close(0);
application.Quit();
workbook = null;
application = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
리소스에서 Excel sheet에 이미지를 추가하려면 이 답변에서 다음 코드를 사용할 수 있습니다. https://stackoverflow.com/a/16979892/8712569
internal static void GenerateExcel()
{
Application excel;
Workbook excelworkBook;
Worksheet excelSheet;
// Start Excel and get Application object.
excel = new Application();
// for making Excel visible
excel.Visible = false;
excel.DisplayAlerts = false;
// Creating a new Workbook
excelworkBook = excel.Workbooks.Add(Type.Missing);
// Get the active sheet
excelSheet = (Worksheet)excelworkBook.ActiveSheet;
excelSheet.Name = "SheetWithImage";
System.Drawing.Bitmap pic = Properties.Resources.my_logo;
System.Windows.Forms.Clipboard.SetImage(pic);
Range position = (Range)excelSheet.Cells[2, 2];
excelSheet.Paste(position); //copy the clipboard to the given position
excelworkBook.SaveAs("MyExcelFile.xlsx", XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excelworkBook.Close();
excel.Quit();
}
언급URL : https://stackoverflow.com/questions/11716873/how-to-insert-a-picture-in-to-excel-from-c-sharp-app
'codememo' 카테고리의 다른 글
| MySQL 비활성화 및 활성화 키 (0) | 2023.09.25 |
|---|---|
| AngularJS 단순 "Hello, world" 작동 안 함 (0) | 2023.09.25 |
| GLib-CRITICAL **: Source ID XXX was not found when attempting to remove it (0) | 2023.09.25 |
| Jquery get input array 필드 (0) | 2023.09.25 |
| Oracle SQL Developer에서 상대 경로별로 스크립트 실행 (0) | 2023.09.20 |