Pasting a CSV file with VBA in Excel is tedious because you have to write a lot of code. I tried to find out if there was an easy way to write in Python.
Paste the CSV contents on the specified sheet of Excel.
Python has several modules for working with Excel. Perhaps the most famous is Openpyxl. However, although Openpyxl has a high processing speed, it has many problems (format collapse, etc.), so This time I would like to use xlwings.
If xlwings is not installed, install it with the following command.
$ pip install xlwings
Since it seems that it will be used frequently in the future, I made it a function. After reading the CSV file with Pandas, it is pasted in cell A1 of the specified sheet. With VBA, it is necessary to read CSV line by line and output it, With Pandas, it's very simple to write.
import pandas as pd
import xlwings as xw
def csv_to_sheet(wb_name, ws_name, csv_name, save_flg=True, quit_flg=True):
"""\
Function description:
A function that copies the contents of CSV to a specified sheet
Argument description:
wb_name: workbook name
ws_name: Sheet name
csv_name: CSV file name
save_flg: Overwrite is performed by default.
quit_flg: Default is closed
"""
df = pd.read_csv(csv_name,encoding='cp932', index_col=0) #Read CSV file with DataFrame
wb = xw.Book(wb_name) #Creating a workbook object
wss = wb.sheets
ws = wss[ws_name] #Creating a worksheet object
ws.range('A1').value = df #Paste DataFrame
#save_Overwrite if flg is True
if save_flg:
wb.save(path=None)
#quit_Close Excel if flg is True
if quit_flg:
app = xw.apps.active
app.quit() #Exit Excel
Please change the Excel file, sheet name, and CSV file to any ones you like. If you do not want to overwrite, set save_flg = False as an argument. If you want to continue editing without closing the file, pass quit_flg = False.
wb_name = 'Excel file name.xlsx'
ws_name = 'Sheet name'
csv_name = 'CSV file'
csv_to_sheet(wb_name, ws_name, csv_name)
Recommended Posts