In writing dataframe to Excel spreadsheet, I want the file to have no border on the first row and column width to be auto adjusted.
With the old package xlwt and xlrd, I can read the file from Pandas produced, to a new file with no border on the header. But it’s .xls (not .xlsx) format.
I can’t make the column width auto adjusted (according to the content of the cells).
The lines looked tedious and troublesome.
What is the Pandas way to do so?
JavaScript
x
42
42
1
import pandas as pd
2
from io import StringIO
3
4
csvfile = StringIO(
5
"""Group Sort String
6
123 207 1st line
7
123 208 2nd line
8
123 209 3rd line
9
123 210 4th line
10
456 625 a1st line
11
456 626 a2nd line
12
456 627 a3rd line
13
""")
14
15
df = pd.read_csv(csvfile, sep = 't', engine='python')
16
df.to_excel("C:\TEM\123.xlsx", index = False)
17
18
from xlwt import Workbook,easyxf,Formula
19
import xlrd
20
import xlwt
21
import xlsxwriter
22
from xlrd import open_workbook
23
24
style = easyxf('borders: left no_line, right no_line, top no_line, bottom no_line;')
25
26
old_file = open_workbook("C:\TEM\123.xlsx")
27
old_sheet = old_file.sheet_by_index(0)
28
29
new_file = xlwt.Workbook(encoding='utf-8', style_compression = 0)
30
new_sheet = new_file.add_sheet('Sheet1', cell_overwrite_ok = True)
31
32
row_data = []
33
for row_index in range(old_sheet.nrows):
34
rows = old_sheet.row_values(row_index)
35
row_data.append(rows)
36
37
for row_index, row in enumerate(row_data):
38
for col_index, cell_value in enumerate(row):
39
new_sheet.write(row_index, col_index, cell_value, style)
40
41
new_file.save('C:\TEM\456.xls')
42
Advertisement
Answer
For the first question, use:
JavaScript
1
2
1
df.T.reset_index().T
2
Demonstration:
JavaScript
1
2
1
df.to_excel('test1.xlsx', index=None)
2
JavaScript
1
2
1
df.T.reset_index().T.to_excel('test2.xlsx', header=None, index=None)
2