python-excel操作

应用xlsxwriter模块,导入测试数据到excel进行绘图并导出

1. 引用:

import xlsxwriter

2. 获取workbook:

workbook = xlsxwriter.Workbook(excel_path)

3. 创建worksheet:

worksheet1 = workbook.add_worksheet("sheet1")

4. 写入行:

headings = ['a', 'b', 'c']
worksheet1.write_row('A1', headings) #从A1单元格开始

5. 写入列:

data1= ['1','2','3']
worksheet1.write_column('A2', data1) #从A2单元格开始

6. 创建折线图:

chart = workbook.add_chart({'type': 'line'})

7. 为折线图指定数据:

values = '=Request!$A$1:$A$' + str(len(data1)) #指定数据区域,此处为从A1开始到data1长度
chart.add_series({'name': 'value', 'values': values}) #指定折线的名称和数据

8. 指定折线图名称:

chart.set_title({'name': 'Request Sequence'})

9. 画出折线图:

worksheet1.insert_chart('C1', chart) #从C1单元格开始画图

10. 关闭workbook:

workbook.close()

11. 散点图:

    chart = workbook.add_chart({'type': 'scatter'})

    # Set data scope
    data_length = len(data1) + 1
    values = '=sheet1!$B$2:$B$' + str(data_length)
    categories = '=sheet1!$A$2:$A$' + str(data_length)

    # Add series
    chart.add_series({'name': 'data1', 'values': values, 'categories': categories})

    # Set chart title and axis labels
    chart.set_title({'name': 'scatter_chart'})
    chart.set_x_axis({'name': 'x'})
    chart.set_y_axis({'name': 'y'})

    # Insert chart
    worksheet1.insert_chart('G1', chart, {'x_scale': 2, 'y_scale': 2}) #x_scale和y_scale用来缩放图形,这里为2倍

12. 使用win32com.client中的Dispatch导出图:

from win32com.client import Dispatch

def export_chart(workbook, worksheet, image_path):
    image_type = 'jpg'

    excel = Dispatch("Excel.Application")
    excel.Visible = True

    wb = excel.Workbooks.Open(workbook)
    sheet = wb.Worksheets(worksheet)

    for chart in sheet.ChartObjects():
        chart.Chart.Export(image_path, image_type)

    wb.Close(False) #如果上面有错误,excel就会保持打开状态,不知道如何解决。
    excel.Quit()

 

posted @ 2019-08-14 14:49  workingdiary  阅读(622)  评论(0编辑  收藏  举报