我在工作表上有多个图表的excel文件。我从excel获取图表并将其保存到图片中。
我的代码:
workSheet = workBook.Sheets[1] as Excel._Worksheet;
Excel.ChartObjects chartObjects =(Excel.ChartObjects)workSheet.ChartObjects(Type.Missing);
int chartCount = chartObjects.Count;
for (int j = 1; j <= chartCount; j++)
{
Excel.ChartObject chart = (Excel.ChartObject)chartObjects.Item(j);
path = Path.Combine(Application.StartupPath, @"Img\" + chart.Chart.Name + ".bmp");
chart.Chart.Export(path, "BMP", true);
}
但只导出空白图片。
请帮帮我
答案 0 :(得分:2)
在调用.Export时导出屏幕上至少部分不可见的图表似乎会产生空白图像。
尝试添加一行代码以在导出之前激活要导出的图表(我遇到了同样的问题,这对我有用):
Excel.ChartObject chart = (Excel.ChartObject)chartObjects.Item(j);
path = Path.Combine(Application.StartupPath, @"Img\" + chart.Chart.Name + ".bmp");
chart.Activate(); //New line
chart.Chart.Export(path, "BMP", true);
答案 1 :(得分:1)
我遇到了同样的问题并尝试了.Activate技巧,但这并没有帮助。基于图表需要至少部分可见的注释,我在.Export行之前尝试了一个简单的延迟循环:
For i = 1 to N
DoEvents
Next i
这解决了这个问题。通过一些实验,我发现N> = 3工作,但如果N = 1或2,或者如果我取出循环,代码返回输出空白图片。我不理解它,但我想我会传递观察结果。
答案 2 :(得分:0)
谢谢@小夫 您花了将近一天的时间为我的小型Python项目寻找解决方案时,您在导出之前在图表激活方面的信息确实对我有所帮助。干杯。
对于正在寻找Python脚本版本以将Excel图表导出为GIF或PNG格式的任何人,下面的代码对我有用:
# Python function to export an Excel chart to a GIF image format
# Ref: https://stackoverflow.com/questions/11110752/export-charts-from-excel-as-images-using-python
def ChartExport(cwd, fileName):
app = win32.Dispatch('Excel.Application')
workbook_file_name = cwd + fileName
workbook = app.Workbooks.Open(Filename=workbook_file_name)
# WARNING: The following line will cause the script to discard any unsaved changes in your workbook
app.DisplayAlerts = False
i = 1 # There are multiple charts on the worksheet. So using a number suffix to add the output gif filename
for sheet in workbook.Worksheets:
for chartObject in sheet.ChartObjects():
#print('i = ', i, ' -- ', sheet.Name + ':' + chartObject.Name)
chartObject.Activate() # This line was added after finding exporting problem with 2nd and 3rd charts. Thanks Xiaofu Ref: https://stackoverflow.com/questions/15911536/excel-chart-export-not-working
chartObject.Chart.Export(cwd + '\\chart' + str(i) + '.gif') # Export chart to a gif file format
i += 1
workbook.Close(SaveChanges=False, Filename=workbook_file_name)
return