vsto 以隐藏的方式打开一个excel 文件 并获得excel文件的缩略图
public byte[] GetExcelPictureFile(string filepath)
{
Workbook workbook=null;
Microsoft.Office.Interop.Excel.Application excelApp = new
Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = false;
string fileName = string.Empty;
try
{
CaCheContext.isUploadingTemplate = true;
workbook= excelApp.Workbooks.Open(filepath, 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
false, false, 0, false, false, false);
fileName = AppDomain.CurrentDomain.BaseDirectory +DateTime.Now.ToString("yyyymmddhhmmss") + workbook.Name;
Sheets worksheets = workbook.Sheets;
int sheetcount = worksheets.Count;
List<string> nameList = new List<string>();
foreach (Worksheet a in worksheets)
{
nameList.Add(a.Name);
}
string firsrName = nameList.First();
Worksheet worksheet = worksheets[firsrName];
worksheet.Range["A1", "E20"].CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);
if (Clipboard.ContainsImage())
{
Image img = Clipboard.GetImage();
Bitmap bitmap = new Bitmap(img);
//保存图片数据
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Jpeg);
byte[] buffer = stream.ToArray();
bitmap.Dispose();
CaCheContext.isUploadingTemplate = false;
Cursor.Current = Cursors.Arrow;
return buffer;
}
else
{
CaCheContext.isUploadingTemplate = false;
Cursor.Current = Cursors.Arrow;
return null;
}
}
catch(Exception ex)
{
Cursor.Current = Cursors.Arrow;
CaCheContext.isUploadingTemplate = false;
MessageBox.Show("生成文件缩略图失败"+ex.Message);
return null;
}
finally
{
workbook.SaveAs(fileName);
workbook.Close();
excelApp.Workbooks.Close();
excelApp.Quit();
excelApp.SendKeys("{TAB}");
excelApp.SendKeys("{ENTER}");
excelApp = null;
this.Focus();
}
}