■102826 / 親階層) |
エクセルのセルの画像化時のエラーについて |
□投稿者/ Massa (1回)-(2024/01/12(Fri) 15:21:06)
|
分類:[C#]
2024/01/12(Fri) 15:43:03 編集(投稿者) 2024/01/12(Fri) 15:33:47 編集(投稿者)
<pre><pre>開発環境は VS2022 C# Framework 4.7.2 WinForms Windows11
指定したセル(P1,P2)がからでない限り Excelのセル範囲を一定間隔でずらしながら,画像として出力するプログラムをC#で作成しています.
以下のようなプログラムを作成したのですが, range.CopPictureのところでエラーになるときとならないときがあり,不安定なってしまいます. エラーメッセージは「range クラスの copypicture メソッドが失敗しました。」と表示されます. 解決法についてご教示いただければ幸いです.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing.Imaging; using Microsoft.Office.Interop.Excel; using System.IO;
namespace Excel2Image { public partial class Form1 : Form {
string excelPath;
int _sheetNum = 6;
int _A1 = 9; int _A2 = 4; int _A3 = 23; int _A4 = 29;
//int _photoNum; int _P1 = 9; int _P2 = 8;
int i = 1; int pageNum = 1;
public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
openFile.Filter = "Excelファイル(*.xls;*.xlsx)|*.xls;*.xlsx"; openFile.FilterIndex = 1; DialogResult result = openFile.ShowDialog();
if (result == DialogResult.OK) { excelPath = openFile.FileName;
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); ExcelApp.Visible = false;
Microsoft.Office.Interop.Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(excelPath);
Worksheet sheet = ExcelWorkbook.Sheets[_sheetNum]; sheet.Select();
while (sheet.Cells[_P1, _P2].Text != "") {
Range range = sheet.Range[sheet.Cells[_A1, _A2], sheet.Cells[_A3, _A4]];
range.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Bitmap)) {
Bitmap bmp = (Bitmap)data.GetData(DataFormats.Bitmap);
bmp.Save(i.ToString() + ".jpg", ImageFormat.Jpeg); i++;
}
if ((flg1 == false) && (flg2 == false)) { flg1 = true; _A1 = 9 + 38 * (pageNum - 1); _A2 = 30; _A3 = 23 + 38 * (pageNum - 1); _A4 = 55;
} else if ((flg1 == true) && (flg2 == false)) { flg2 = true; _A1 = 24 + 38 * (pageNum - 1); _A2 = 4; _A3 = 38 + 38 * (pageNum - 1); _A4 = 29;
} else if ((flg1 == true) && (flg2 == true)) { flg1 = false; _A1 = 24 + 38 * (pageNum - 1); _A2 = 30; _A3 = 38 + 38 * (pageNum - 1); _A4 = 55;
} else if ((flg1 == false) && (flg2 == true)) { pageNum++; flg2 = false;
_A1 = 9 + 38 * (pageNum - 1); _A2 = 4; _A3 = 23 + 38 * (pageNum - 1); _A4 = 29;
}
_P1 = _A1; _P2 = _A2 + 4;
} ExcelApp.Quit(); } }</pre></pre>
|
|