Hướng dẫn convert multiple csv to excel sheets python - chuyển đổi nhiều trang csv thành excel python

Tôi đang cố gắng chuyển đổi tất cả các tệp CSV trong thư mục thành một tệp XLXS với mỗi tệp CSV trở thành một bảng tính riêng biệt.

Mã bên dưới hoạt động ngoại trừ khi tôi cung cấp đường dẫn đầu vào trong dòng này "cho tên tệp trên glob.glob (inputPath +"*.csv "):" Tôi gặp lỗi này - không hợp lệ trong bảng tênInputPath + "*.csv"):" I get this error - InvalidWorksheetName: Invalid Excel character '[]:*?/' in sheetname

Có ai có một gợi ý làm thế nào tôi có thể đi xung quanh điều này? Mã đầy đủ dưới đây - cảm ơn!

import xlsxwriter
import glob
import csv

InputPath = r"C:\\Users\\.spyder-py3\\"

workbook = xlsxwriter.Workbook(r"C:\\Users\\.spyder-py3\\Output\\compiled.xlsx") 
for filename in glob.glob(InputPath + "\*.csv"):
ws = workbook.add_worksheet(str(filename.split('.')[0]))
spamReader = csv.reader(open(filename, 'r'), delimiter=',',quotechar='"')
row_count = 0
print(filename)
for row in spamReader:
    for col in range(len(row)):
        ws.write(row_count,col,row[col])
    row_count +=1

workbook.close()

hỏi ngày 14 tháng 3 lúc 14:30Mar 14 at 14:30

Hướng dẫn convert multiple csv to excel sheets python - chuyển đổi nhiều trang csv thành excel python

Thử cái này:

import xlsxwriter
import glob
import csv

InputPath = r"C:\Users\.spyder-py3"

workbook = xlsxwriter.Workbook(r"C:\Users\.spyder-py3\Output\compiled.xlsx") 
for filename in glob.glob(InputPath + r"\*.csv"):
    ws = workbook.add_worksheet(str(filename.split('.')[0]))
    spamReader = csv.reader(open(filename, 'r'), delimiter=',',quotechar='"')
    row_count = 0
    print(filename)
    for row in spamReader:
        for col in range(len(row)):
            ws.write(row_count,col,row[col])
        row_count +=1

workbook.close()

Đã trả lời ngày 14 tháng 3 lúc 14:43Mar 14 at 14:43

VovinvovinVovin

6223 Huy hiệu bạc15 Huy hiệu Đồng3 silver badges15 bronze badges

2

  • Tạo và đọc các tệp CSV
  • Đọc CSV
  • Tạo tờ Excel
  • Chuyển đổi một tệp CSV đơn thành nhiều tờ
  • Chuyển đổi nhiều tệp CSV thành bảng Excel

Ngôn ngữ lập trình Python có nhiều thư viện có thể đọc, viết và thao tác các tệp CSV. Mô-đun CSV tích hợp của Python là một trong những thư viện như vậy. Nó có thể được sử dụng để đọc hoặc viết nội dung của tệp CSV hoặc để phân tích nó thành các chuỗi, số, v.v.csv module is one such library. It can be used to read or write the contents of a CSV file or to parse it into individual strings, numbers, etc.

Khi nói đến việc chuyển đổi CSV thành tệp Excel, chúng ta phải sử dụng một mô -đun bên ngoài cho phép chúng ta làm việc với các tệp Excel (XLSX). Có một vài thư viện như vậy để lựa chọn.xlsx). There are few such libraries to choose from.

Đối với bài viết này, chúng tôi sẽ sử dụng mô -đun XLSXWriter.xlsxwriter module.

Nội dung

  • 1 Tạo và đọc các tệp CSV Create and read CSV files
  • 2 Đọc CSV Read CSV
  • 3 Tạo tờ Excel Create Excel Sheet
  • 4 Chuyển đổi một tệp CSV đơn thành nhiều tờ Convert a single CSV file to multiple sheets
  • 5 chuyển đổi nhiều tệp CSV thành các tờ Excel Convert multiple CSV files to Excel sheets

Tạo và đọc các tệp CSV

Đọc CSV

import csv

with open('writers.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["#", "Name", "Book", "Gender"])
    writer.writerow([1, "Agatha Christie", "Murder on the Orient Express", "Female"])
    writer.writerow([2, "J. K. Rowling", "Harry Potter", "Female"])
    writer.writerow([3, "J. R. R. Tolkien", "Lord of the Rings", "Male"])
    writer.writerow([4, "Stephen King", "The Shining", "Male"])
    writer.writerow([5, "Danielle Steel", "Invisible", "Female"])
    writer.writerow([6, "William Shakespeare", "Hamlet", "Male"])

Tạo tờ Excel

Hướng dẫn convert multiple csv to excel sheets python - chuyển đổi nhiều trang csv thành excel python

Đọc CSV

Tạo tờ Excel

Chuyển đổi một tệp CSV đơn thành nhiều tờ

Tạo tờ Excel

Chuyển đổi một tệp CSV đơn thành nhiều tờ

import xlsxwriter

workbook = xlsxwriter.Workbook('writers.xlsx')
worksheet1 = workbook.add_worksheet('Male')
worksheet2 = workbook.add_worksheet('Female')
workbook.close()

Chuyển đổi nhiều tệp CSV thành bảng Excelwriters.xslx with two worksheets: Male and Female.

Hướng dẫn convert multiple csv to excel sheets python - chuyển đổi nhiều trang csv thành excel python

Ngôn ngữ lập trình Python có nhiều thư viện có thể đọc, viết và thao tác các tệp CSV. Mô-đun CSV tích hợp của Python là một trong những thư viện như vậy. Nó có thể được sử dụng để đọc hoặc viết nội dung của tệp CSV hoặc để phân tích nó thành các chuỗi, số, v.v.close function. Without it, the file won’t be created.

Chuyển đổi một tệp CSV đơn thành nhiều tờ

Chuyển đổi nhiều tệp CSV thành bảng Excel

for index in range(len(header)):
    worksheet1.write(0, index, header[index])
    worksheet2.write(0, index, header[index])

Ngôn ngữ lập trình Python có nhiều thư viện có thể đọc, viết và thao tác các tệp CSV. Mô-đun CSV tích hợp của Python là một trong những thư viện như vậy. Nó có thể được sử dụng để đọc hoặc viết nội dung của tệp CSV hoặc để phân tích nó thành các chuỗi, số, v.v.A or row 1.

Khi nói đến việc chuyển đổi CSV thành tệp Excel, chúng ta phải sử dụng một mô -đun bên ngoài cho phép chúng ta làm việc với các tệp Excel (XLSX). Có một vài thư viện như vậy để lựa chọn.index starts from the first column and takes the first element from the list, then the second column and the second element.

Hướng dẫn convert multiple csv to excel sheets python - chuyển đổi nhiều trang csv thành excel python

Đối với bài viết này, chúng tôi sẽ sử dụng mô -đun XLSXWriter.

row_numer_male = 0
row_numer_female = 0

for row in csvreader:
    if row[3] == 'Male':
        row_numer_male += 1
        for index in range(len(header)):
            worksheet1.write(row_numer_male, index, row[index])
    elif row[3] == 'Female':
        row_numer_female += 1
        for index in range(len(header)):
            worksheet2.write(row_numer_female, index, row[index])

Nội dungMale, the element is placed inside the first worksheet, if it’s Female, then into the second one.

1 Tạo và đọc các tệp CSV

Hướng dẫn convert multiple csv to excel sheets python - chuyển đổi nhiều trang csv thành excel python

2 Đọc CSV

Hướng dẫn convert multiple csv to excel sheets python - chuyển đổi nhiều trang csv thành excel python

3 Tạo tờ Excel

import csv
import xlsxwriter

with open('writers.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["#", "Name", "Book", "Gender"])
    writer.writerow([1, "Agatha Christie", "Murder on the Orient Express", "Female"])
    writer.writerow([2, "J. K. Rowling", "Harry Potter", "Female"])
    writer.writerow([3, "J. R. R. Tolkien", "Lord of the Rings", "Male"])
    writer.writerow([4, "Stephen King", "The Shining", "Male"])
    writer.writerow([5, "Danielle Steel", "Invisible", "Female"])
    writer.writerow([6, "William Shakespeare", "Hamlet", "Male"])


file = open("writers.csv")
csvreader = csv.reader(file)
header = next(csvreader)

workbook = xlsxwriter.Workbook('writers.xlsx')
worksheet1 = workbook.add_worksheet('Male')
worksheet2 = workbook.add_worksheet('Female')

for index in range(len(header)):
    worksheet1.write(0, index, header[index])
    worksheet2.write(0, index, header[index])

row_numer_male = 0
row_numer_female = 0

for row in csvreader:
    if row[3] == 'Male':
        row_numer_male += 1
        for index in range(len(header)):
            worksheet1.write(row_numer_male, index, row[index])
    elif row[3] == 'Female':
        row_numer_female += 1
        for index in range(len(header)):
            worksheet2.write(row_numer_female, index, row[index])

file.close()
workbook.close()

Chuyển đổi nhiều tệp CSV thành bảng Excel

Chúng ta có thể có một cách tiếp cận khác. Nếu chúng ta có nhiều tệp CSV bên trong một thư mục, chúng ta có thể chuyển đổi từng tệp thành một bảng tính Excel được đặt tên theo tệp này.

Chúng tôi có thể sửa đổi mã trước đó để tạo hai tệp CSV, một cho nữ và một cho các nhà văn nam:

with open('female_writers.csv', 'w', newline='') as file:
    writer = csv.writer(file)

    writer.writerow(["#", "Name", "Book", "Gender"])
    writer.writerow([1, "Agatha Christie", "Murder on the Orient Express", "Female"])
    writer.writerow([2, "J. K. Rowling", "Harry Potter", "Female"])
    writer.writerow([5, "Danielle Steel", "Invisible", "Female"])

with open('male_writers.csv', 'w', newline='') as file:
    writer = csv.writer(file)

    writer.writerow(["#", "Name", "Book", "Gender"])
    writer.writerow([3, "J. R. R. Tolkien", "Lord of the Rings", "Male"])
    writer.writerow([4, "Stephen King", "The Shining", "Male"])
    writer.writerow([6, "William Shakespeare", "Hamlet", "Male"])

Tiếp theo, hãy để đọc các tệp CSV.

Có một vài cách chúng ta có thể sử dụng để có được tất cả các tệp với một tiện ích mở rộng nhất định; Sử dụng mô -đun GLOB là một trong số đó.glob module is one of them.

import glob
import os

files = glob.glob(r'C:\path\*csv')

for file_path in files:
    print(file)

Mã trên có tất cả các tệp CSV từ thư mục và in chúng vào bảng điều khiển.

Những gì chúng ta cần làm bây giờ là tạo một tệp Excel và sử dụng tên tệp CSV làm tên bảng tính. Chúng tôi cũng cần sao chép nội dung của mỗi tệp CSV vào mỗi trang. Mã sau đây làm điều đó.

import xlsxwriter
import glob
import csv

InputPath = r"C:\Users\.spyder-py3"

workbook = xlsxwriter.Workbook(r"C:\Users\.spyder-py3\Output\compiled.xlsx") 
for filename in glob.glob(InputPath + r"\*.csv"):
    ws = workbook.add_worksheet(str(filename.split('.')[0]))
    spamReader = csv.reader(open(filename, 'r'), delimiter=',',quotechar='"')
    row_count = 0
    print(filename)
    for row in spamReader:
        for col in range(len(row)):
            ws.write(row_count,col,row[col])
        row_count +=1

workbook.close()
0

Chức năng OS.Path.Basename dải đường dẫn tệp đầy đủ và chỉ gán một tên cho biến FILE_NAME. Tiếp theo, phần mở rộng tên (với) này được chia thành phần mở rộng tên tệp và tệp, trong đó đường dẫn tên được gán cho file_no_ext.os.path.basename function strips the full file path and assigns only a name to the file_name variable. Next, this name (with) extension is split into the file name and file extension, where the name path is assigned to file_no_ext.

Mỗi bảng tính được đặt tên bằng cách sử dụng biến này.

Hướng dẫn convert multiple csv to excel sheets python - chuyển đổi nhiều trang csv thành excel python