如何在保留日期值的同时将 n 行 xlsx 转换为 Python 中的 csv
How to convert n rows of xlsx to csv in Python while preserving date values
我正在尝试将一个 xlsx 文件转换为一个包含 header 的 CSV 文件和另一个包含实际数据的 CSV 文件。
我有以下要求:
- Header 不是从第一行开始,而是从第
start_line
行开始。
- 日期不应视为浮点数,而应视为某种字符串格式。
- 我事先不知道文件的总行数或列数。我也不想指定哪一列是日期。
使用 pandas
我卡在了数字 1。
我想通过两次单独的阅读来实现这一点,我从 start_line 阅读到 start_line+1
以及从 start_line+1
阅读到结尾。
但是,从偏移量读取 n 行似乎是 。下面是我用来获取一个文件的代码,包括 header.
import pandas as pd
def parse_excel(file,start_line,sheet,table):
sh = pd.read_excel(file,sheet,skiprows=start_line)
sh.to_csv("output.csv",sep='\t',encoding='utf-8',index=False)
接下来我使用 xlrd
进行了尝试,但是这个库将所有日期都视为浮点数,就像 Excel 中那样。这里唯一的解决方法似乎是 go through all individual cells,它似乎效率不高或编码不当。我现在拥有的:
import xlrd
def parse_excel(file,start_line,sheet,table):
with xlrd.open_workbook(file) as wb:
sh = wb.sheet_by_name(sheet)
header_written = False
with open('{0}.csv'.format(table),'wb') as csv_file:
wr = csv.writer(csv_file,delimiter='\t')
for rownum in range(sh.nrows):
if not header_written and start_line == rownum:
with open('{0}_header.csv'.format(table),'wb') as header:
hwr = csv.writer(header,delimiter='\t')
hwr.writerow(sh.row_values(rownum))
header_written = True
elif header_written:
wr.writerow(sh.row_values(rownum))
请向我指出其他 solutions/libraries,显示上述任一方法的解决方法,或解释为什么我应该使用 xlrd
解决方法检查每个单独的单元格。
只要您的所有数据都在 header 行下方,那么下面的操作应该有效。假设 header 行位于 n
行(索引从 0 开始,而不是像 excel 那样的 1)。
df = pd.read_excel('filepath', header=n)
df.head(0).to_csv('header.csv', index=False)
df.to_csv('output.csv', header=None, index=False)
我正在尝试将一个 xlsx 文件转换为一个包含 header 的 CSV 文件和另一个包含实际数据的 CSV 文件。 我有以下要求:
- Header 不是从第一行开始,而是从第
start_line
行开始。 - 日期不应视为浮点数,而应视为某种字符串格式。
- 我事先不知道文件的总行数或列数。我也不想指定哪一列是日期。
使用 pandas
我卡在了数字 1。
我想通过两次单独的阅读来实现这一点,我从 start_line 阅读到 start_line+1
以及从 start_line+1
阅读到结尾。
但是,从偏移量读取 n 行似乎是
import pandas as pd
def parse_excel(file,start_line,sheet,table):
sh = pd.read_excel(file,sheet,skiprows=start_line)
sh.to_csv("output.csv",sep='\t',encoding='utf-8',index=False)
接下来我使用 xlrd
进行了尝试,但是这个库将所有日期都视为浮点数,就像 Excel 中那样。这里唯一的解决方法似乎是 go through all individual cells,它似乎效率不高或编码不当。我现在拥有的:
import xlrd
def parse_excel(file,start_line,sheet,table):
with xlrd.open_workbook(file) as wb:
sh = wb.sheet_by_name(sheet)
header_written = False
with open('{0}.csv'.format(table),'wb') as csv_file:
wr = csv.writer(csv_file,delimiter='\t')
for rownum in range(sh.nrows):
if not header_written and start_line == rownum:
with open('{0}_header.csv'.format(table),'wb') as header:
hwr = csv.writer(header,delimiter='\t')
hwr.writerow(sh.row_values(rownum))
header_written = True
elif header_written:
wr.writerow(sh.row_values(rownum))
请向我指出其他 solutions/libraries,显示上述任一方法的解决方法,或解释为什么我应该使用 xlrd
解决方法检查每个单独的单元格。
只要您的所有数据都在 header 行下方,那么下面的操作应该有效。假设 header 行位于 n
行(索引从 0 开始,而不是像 excel 那样的 1)。
df = pd.read_excel('filepath', header=n)
df.head(0).to_csv('header.csv', index=False)
df.to_csv('output.csv', header=None, index=False)