I've looked at this for some time now and I can't find any obvious issue. I have a refreshable workbook that is linked to SQL. I need to open the workbook, refresh the data connection, save the workbook, copy a range of cells as an image and paste it into an email. It works about 50% of the time and the other 50% I get a CopyPicture method of Range class failed
error.
Any help is appreciated.
here is a code snippet:
namespace Scorecard
{
class SpreadsheetRefresh
{
public void Execute()
{
public Excel.Application xlApp;
public Excel.Workbook xlWorkbook;
public Excel.Worksheet xlWorksheet;
DateTime reportDate = DateTime.Now.AddDays(-1).Date;
string stringDate = reportDate.ToString("d");
try
{
xlApp = new Excel.Application
{
Visible = true,
DisplayAlerts = true
};
xlWorkbook = xlApp.Workbooks.Open("c:\workbook.xlsx");
xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item("Report");
xlWorksheet.Cells[3, 3] = stringDate;
xlWorksheet.Cells[4, 3] = stringDate;
var task = Task.Run(() => refreshWorkbook());
if (!task.Wait(TimeSpan.FromSeconds(60)))
{
throw new Exception("The data refresh failed due to a timeout - please try again or refresh manually.");
}
Excel.Range StartCell = xlWorksheet.Cells[12, 2] as Excel.Range;
Excel.Range EndCell = xlWorksheet.Cells[17, 21] as Excel.Range;
Excel.Range ImageRange = xlWorksheet.Range[StartCell, EndCell] as Excel.Range;
ImageRange.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlBitmap);
using (FileStream filestream = new FileStream(baseImageOneName, FileMode.Create))
{
BitmapSource bitmapSource = Clipboard.GetData(DataFormats.Bitmap) as BitmapSource;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.QualityLevel = 100;
encoder.Save(filestream);
}
xlWorkbook.Save();
xlWorkbook.Close(false);
xlApp.Quit();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}