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

372 views Asked by At

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()
2

There are 2 answers

0
Ashish Shirodkar On BEST ANSWER

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.

0
AudioBubble On

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()