简体   繁体   中英

### Character when open a CSV File in Excel Created Using Python

I am created a CSV File in python.So it created a csv file.When i opened that file in excel some #### characters are shown.When i increase the width of that column manually it prints the original data. By programmically any chances are there to increase the width of that column.Sample code is shown below.Thanks in advance for your replies.

import csv
from datetime import datetime

csvData = ([[datetime.now().date(), datetime.now().time().strftime("%I:%M:%S %p")]])
with open('test.csv', 'a') as csvFile:
    writer = csv.writer(csvFile, delimiter=',', quoting=csv.QUOTE_ALL, 
             lineterminator='\n')
    writer.writerows(csvData)
csvFile.close()

CSV=Comma Separated Values, it does not have any properties associated with values, hence excel uses its default settings to display its values. For writing an *.xls file you may use xlwt module, and for *.xlsx files XlsxWriter module.

This is because of the width of the column being smaller than the contents of the column. When you export a CSV file from python this tends to happen as there is no autofit() function for the CSV file. You can however expand the column width by manually dragging to display the actual contents of the column instead of ####.

You can also use the following code if you want to automatically adjust the width of the columns while exporting an EXCEL file from python.

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'file_path.xlsx')
ws_1 = wb.Worksheets("Sheet 1")
ws_1.Columns.AutoFit()
ws_2 = wb.Worksheets("Sheet 2")
ws_2.Columns.AutoFit()
wb.Save()
excel.Application.Quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM