PIbd-33_Abazov_A.A._KOP_29/AbazovApp/AbazovViewComponents/LogicalComponents/ExcelImagesComponent.cs

75 lines
2.5 KiB
C#
Raw Normal View History

2023-10-15 15:18:36 +04:00
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
namespace AbazovViewComponents.LogicalComponents
{
public partial class ExcelImagesComponent : Component
{
public ExcelImagesComponent()
{
InitializeComponent();
}
public ExcelImagesComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public bool createWithImages(ExcelImageInfo info)
{
var excelApp = new Microsoft.Office.Interop.Excel.Application { SheetsInNewWorkbook = 1 };
Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
try
{
//create
Worksheet worksheet = (Worksheet)workbook.Worksheets.get_Item(1);
//header
var excelcells = worksheet.get_Range("A1", "D1");
excelcells.Merge(Type.Missing);
excelcells.Font.Bold = true;
excelcells.Font.Size = 14;
excelcells.Font.Name = "Times New Roman";
excelcells.ColumnWidth = 8;
excelcells.RowHeight = 25;
excelcells.HorizontalAlignment = Constants.xlCenter;
excelcells.VerticalAlignment = Constants.xlCenter;
excelcells.Value2 = info.title;
int topOffset = 25;
foreach (string path in info.imagePaths)
{
Bitmap bm = new Bitmap(path);
worksheet.Shapes.AddPicture2(path, MsoTriState.msoFalse, MsoTriState.msoCTrue, 0, topOffset, bm.Width, bm.Height, MsoPictureCompress.msoPictureCompressFalse);
topOffset += bm.Height;
bm.Dispose();
}
//save
object missing = System.Reflection.Missing.Value;
workbook.SaveAs(info.path, XlFileFormat.xlOpenXMLWorkbook, missing, missing, false, false, XlSaveAsAccessMode.xlNoChange,
XlSaveConflictResolution.xlUserResolution, true, missing, missing, missing);
workbook.Close();
excelApp.Quit();
return true;
}
catch (Exception)
{
workbook.Close();
excelApp.Quit();
return false;
}
}
}
}