以编程方式(C#)将Excel转换为图像 [英] Programmatically (C#) convert Excel to an image

查看:757
本文介绍了以编程方式(C#)将Excel转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式(c#)将excel文件转换为图像(每种格式都可以)。目前我正在使用Microsoft Interop Libraries& Office 2007,但它不支持默认保存到图像。



所以我目前的解决方法如下:




  • 使用Microsoft Interop打开Excel文件;

  • 找出最大范围(包含数据);

  • 使用该范围上的CopyPicture(),将数据复制到剪贴板。



现在是棘手的部分(和我的问题1:



使用.NET Clipboard类,我无法从剪贴板中获取EXACT复制的数据:数据是相同的,但是不知何故格式化是扭曲的(整个文档的字体似乎变得粗体,并且在它们没有时更不可读);如果我使用mspaint.exe从剪贴板粘贴,粘贴的图像是正确的(就像我想要的那样)。



我反汇编了mspaint.exe,发现它正在使用的功能(OleGetClipboard)从剪贴板获取数据,但我似乎无法使其在C#/中工作。 NET。



我尝试的其他东西是剪贴板WINAPI(OpenClipboard,GetClipboardData,CF_ENHMETAFILE),但结果与使用.NET版本相同。



问题2:



使用范围和CopyPicture,如果excel中有任何图像



某些源代码

  Excel.Application app = new Excel.Application(); 
app.Visible = app.ScreenUpdating = app.DisplayAlerts = false;
app.CopyObjectsWithCells = true;
app.CutCopyMode = Excel.XlCutCopyMode.xlCopy;
app.DisplayClipboardWindow = false;

try {
Excel.Workbooks workbooks = null;
Excel.Workbook book = null;
Excel.Sheets sheets = null;

try {
workbooks = app.Workbooks;
book = workbooks.Open(inputFile,false,false,Type.Missing,Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type。缺少,Type.Missing,Type.Missing,
Type.Missing,Type.Missing);
sheets = book.Worksheets;
} catch {
清理(工作簿,书籍,工作表); //清理功能为所有传递的对象调用Marshal.ReleaseComObject
throw; (int i = 0; i< sheets.Count; i ++){
Excel.Worksheet sheet =(Excel.Worksheet)sheets.get_Item(i + 1);

Excel.Range myrange = sheet.UsedRange;
Excel.Range rowRange = myrange.Rows;
Excel.Range colRange = myrange.Columns;

int rows = rowRange.Count;
int cols = colRange.Count;

//以下用于查找数据的范围
string startRange =A1;
string endRange = ExcelColumnFromNumber(cols)+ rows.ToString();

//跳过空excel表
if(startRange == endRange){
Excel.Range firstRange = sheet.get_Range(startRange,endRange);
Excel.Range cellRange = firstRange.Cells;
object text = cellRange.Text;
string strText = text.ToString();
string trimmed = strText.Trim();

if(trimmed ==){
清理(trimmed,strText,text,cellRange,firstRange,myrange,rowRange,colRange,sheet);
继续;
}
清理(trimmed,strText,text,cellRange,firstRange);
}

Excel.Range范围= sheet.get_Range(startRange,endRange);
try {
range.CopyPicture(Excel.XlPictureAppearance.xlScreen,Excel.XlCopyPictureFormat.xlPicture);

//问题在这里< -------------
//每次尝试从剪贴板获取数据失败
} finally {
清理(范围);
清理(myrange,rowRange,colRange,sheet);
}
} // end for loop

book.Close(false,Type.Missing,Type.Missing);
workbooks.Close();

清理(书,表,工作簿);
} finally {
app.Quit();
清理(app);
GC.Collect();
}

使用WINAPI从剪贴板获取数据成功,但质量差。来源:

  protected virtual void ClipboardToPNG(string filename){
if(OpenClipboard(IntPtr.Zero)){
if(IsClipboardFormatAvailable((int)CLIPFORMAT.CF_ENHMETAFILE)){
int hEmfClp = GetClipboardDataA((int)CLIPFORMAT.CF_ENHMETAFILE);

if(hEmfClp!= 0){
int hEmfCopy = CopyEnhMetaFileA(hEmfClp,null);

if(hEmfCopy!= 0){
图元文件元文件=新的图元文件(新的IntPtr(hEmfCopy),true);

metafile.Save(filename,ImageFormat.Png);
}
}
}

CloseClipboard();
}
}

任何人都有解决方案? (我正在使用.NET 2.0 btw)

解决方案

SpreadsheetGear for .NET 将执行此操作。



您可以看到我们的ASP.NET(C#和VB) Excel图表和范围成像样本示例 here 并下载如果您想尝试一下免费试用版此处



SpreadsheetGear还适用于Windows窗体,控制台应用程序等(您没有指定要创建哪种类型的应用程序)。还有一个Windows窗体控件可以在您的应用程序中显示工作簿,如果这是您真正的后期。



免责声明:我拥有SpreadsheetGear LLC


I want to convert an excel file to an image (every format is ok) programmatically (c#). Currently I'm using Microsoft Interop Libraries & Office 2007, but it does not support saving to an image by default.

So my current work-around is as follows:

  • Open Excel file using Microsoft Interop;
  • Find out the max range (that contains data);
  • Use the CopyPicture() on that range, which will copy the data to the Clipboard.

Now the tricky part (and my problems):

Problem 1:

Using the .NET Clipboard class, I'm not able to get the EXACT copied data from the clipboard: the data is the same, but somehow the formatting is distorted (the font of the whole document seems to become bold and a little bit more unreadable while they were not); If I paste from the clipboard using mspaint.exe, the pasted image is correct (and just as I want it to be).

I disassembled mspaint.exe and found a function that it is using (OleGetClipboard) to get data from the clipboard, but I cannot seem to get it working in C# / .NET.

Other things I tried were the Clipboard WINAPI's (OpenClipboard, GetClipboardData, CF_ENHMETAFILE), but the results were the same as using the .NET versions.

Problem 2:

Using the range and CopyPicture, if there are any images in the excel sheet, those images are not copied along with the surrounding data to the clipboard.

Some of the source code

Excel.Application app = new Excel.Application();
app.Visible = app.ScreenUpdating = app.DisplayAlerts = false;
app.CopyObjectsWithCells = true;
app.CutCopyMode = Excel.XlCutCopyMode.xlCopy;
app.DisplayClipboardWindow = false;

try {
    Excel.Workbooks workbooks = null;
    Excel.Workbook book = null;
    Excel.Sheets sheets = null;

    try {
        workbooks = app.Workbooks;
        book = workbooks.Open(inputFile, false, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                              Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                              Type.Missing, Type.Missing);
        sheets = book.Worksheets;
    } catch {
        Cleanup(workbooks, book, sheets);   //Cleanup function calls Marshal.ReleaseComObject for all passed objects
        throw;
    }

    for (int i = 0; i < sheets.Count; i++) {
        Excel.Worksheet sheet = (Excel.Worksheet)sheets.get_Item(i + 1);

        Excel.Range myrange = sheet.UsedRange;
        Excel.Range rowRange = myrange.Rows;
        Excel.Range colRange = myrange.Columns;

        int rows = rowRange.Count;
        int cols = colRange.Count;

        //Following is used to find range with data
        string startRange = "A1";
        string endRange = ExcelColumnFromNumber(cols) + rows.ToString();

        //Skip "empty" excel sheets
        if (startRange == endRange) {
            Excel.Range firstRange = sheet.get_Range(startRange, endRange);
            Excel.Range cellRange = firstRange.Cells;
            object text = cellRange.Text;
            string strText = text.ToString();
            string trimmed = strText.Trim();

            if (trimmed == "") {
                Cleanup(trimmed, strText, text, cellRange, firstRange, myrange, rowRange, colRange, sheet);
                continue;
            }
            Cleanup(trimmed, strText, text, cellRange, firstRange);
        }

        Excel.Range range = sheet.get_Range(startRange, endRange);
        try {
            range.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlPicture);

            //Problem here <-------------
            //Every attempt to get data from Clipboard fails
        } finally {
            Cleanup(range);
            Cleanup(myrange, rowRange, colRange, sheet);
        }
    }   //end for loop

    book.Close(false, Type.Missing, Type.Missing);
    workbooks.Close();

    Cleanup(book, sheets, workbooks);
} finally {
    app.Quit();
    Cleanup(app);
    GC.Collect();
}

Getting data from the clipboard using WINAPI succeeds, but with bad quality. Source:

protected virtual void ClipboardToPNG(string filename) {
    if (OpenClipboard(IntPtr.Zero)) {
        if (IsClipboardFormatAvailable((int)CLIPFORMAT.CF_ENHMETAFILE)) {
            int hEmfClp = GetClipboardDataA((int)CLIPFORMAT.CF_ENHMETAFILE);

            if (hEmfClp != 0) {
                int hEmfCopy = CopyEnhMetaFileA(hEmfClp, null);

                if (hEmfCopy != 0) {
                    Metafile metafile = new Metafile(new IntPtr(hEmfCopy), true);

                    metafile.Save(filename, ImageFormat.Png);
                }
            }
        }

        CloseClipboard();
    }
}

Anyone got a solution? (I'm using .NET 2.0 btw)

解决方案

SpreadsheetGear for .NET will do it.

You can see our ASP.NET (C# and VB) "Excel Chart and Range Imaging Samples" samples here and download a free trial here if you want to try it out.

SpreadsheetGear also works with Windows Forms, console applications, etc... (you did not specify what type of application you are creating). There is also a Windows Forms control to display a workbook in your application if that is what you are really after.

Disclaimer: I own SpreadsheetGear LLC

这篇关于以编程方式(C#)将Excel转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆