I have an Excel spreadsheet which is one sheet with a table and chart in it. What I need to do is add this to a PDF. The PDF API I am using does not support importing Excel documents so I wondered if there is any way from C++ to save/convert an Excel document to a Jpeg (or BMP)?
Just to add, obviously this has to be done in C++ as part of an existing application which creates PDFs every time it is run. I wouldn't be asking the question if it was a one off that could just be done manually.
Well I have, after much effort and hair pulling, managed to answer my own question. Contrary to what was said in other answers, it is possible to save an Excel spreadsheet as Jpeg (although I have stuck to bitmap format as that's good enough for me. It would be easy enough to convert to jpeg though). What I did via the Excel API was select the used range. From there, I copy this to the clipboard as a picture, then get the clipboard data and convert it to a picture object with an IPicture interface. From there, create a stream and copy this to the stream before saving this stream to file. The
{
CRange range = sheet.get_UsedRange();
range.CopyPicture(Excel::xlScreen, Excel::xlBitmap);
if (IsClipboardFormatAvailable(CF_BITMAP)) // just to be sure it copied
{
if (OpenClipboard(NULL) > 0)
{
// save clipboard as bmp
HBITMAP hBitmap = (HBITMAP)GetClipboardData(CF_BITMAP);
SaveBitmap(ps_filename, hBitmap, NULL);
CloseClipboard();
}
}
}
bool CExcelDocument::SaveBitmap(LPCSTR filename, HBITMAP bmp, HPALETTE pal)
{
bool bReturn = false;
PICTDESC pictdesc;
LPPICTURE pPicture;
::ZeroMemory( &pictdesc, sizeof(pictdesc) );
pictdesc.picType = PICTYPE_BITMAP;
pictdesc.bmp.hbitmap = bmp;
pictdesc.bmp.hpal = pal;
pictdesc.cbSizeofstruct = sizeof(PICTDESC);
HRESULT hr = OleCreatePictureIndirect(&pictdesc, IID_IPicture, false, reinterpret_cast<void**>(&pPicture));
if (!SUCCEEDED(hr))
return false;
LPSTREAM pStream;
hr = CreateStreamOnHGlobal(0, true, &pStream);
if (!SUCCEEDED(hr))
{
pPicture->Release();
return false;
}
LONG lBytesRead = 0;
DWORD lBytesWritten = 0;
hr = pPicture->SaveAsFile(pStream, true, &lBytesRead);
if (!SUCCEEDED(hr))
{
pStream->Release();
pPicture->Release();
return false;
}
HANDLE hFile = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (!hFile)
{
return false;
}
HGLOBAL hMemory = 0;
GetHGlobalFromStream(pStream, &hMemory);
LPVOID pData = GlobalLock(hMemory);
bReturn = !!WriteFile(hFile, pData, lBytesRead, &lBytesWritten, 0);
bReturn &= (lBytesWritten == static_cast<DWORD>(lBytesRead));
GlobalUnlock(hMemory);
CloseHandle(hFile);
pStream->Release();
pPicture->Release();
return bReturn;
}
result is a bmp file with exactly the image I was after. Code sample below.