1
1
import openpyxl
2
- import sys
2
+ import os
3
3
4
+ # Get the CSV and Excel file names from the user
4
5
csv_name = input ("Name of the input CSV file with extension: " )
5
6
sep = input ("Separator of the CSV file: " )
6
- ename = input ("Name of the output excel file with extension: " )
7
- sname = input ("Name of the output excel sheet: " )
7
+ excel_name = input ("Name of the output excel file with extension: " )
8
+ sheet_name = input ("Name of the output excel sheet: " )
9
+
10
+ # Load the CSV file
11
+ if os .path .exists (excel_name ):
12
+ workbook = openpyxl .load_workbook (excel_name )
13
+ sheet = workbook [sheet_name ] if sheet_name in workbook .sheetnames else workbook .create_sheet (sheet_name )
14
+ else :
15
+ workbook = openpyxl .Workbook ()
16
+ sheet = workbook .active
17
+ sheet .title = sheet_name
18
+
19
+ # Write the CSV data to the Excel sheet
8
20
try :
9
- workbook = openpyxl .load_workbook (ename )
10
- sheet = workbook .get_sheet_by_name (sname )
11
-
12
- file = open (csv_name , "r" , encoding = "utf-8" )
13
- except :
14
- print ("Error: File not found" )
15
- sys .exit ()
16
- excel_row = 1
17
- excel_column = 1
18
-
19
- for lines in file :
20
-
21
- lines = lines [:- 1 ]
22
- lines = lines .split (sep )
23
-
24
- for dat in lines :
25
-
26
- sheet .cell (excel_row , excel_column ).value = dat
27
-
28
- excel_column += 1
29
-
30
- excel_column = 1
31
- excel_row += 1
32
-
33
-
34
- workbook .save (ename )
35
- file .close ()
36
-
37
- csv_name = input ("Name of the input CSV file with extension: " )
38
- sep = input ("Separator of the CSV file: " )
39
- ename = input ("Name of the output excel file with extension: " )
40
- sname = input ("Name of the output excel sheet: " )
41
- try :
42
- workbook = openpyxl .load_workbook (ename )
43
- sheet = workbook .get_sheet_by_name (sname )
44
-
45
- file = open (csv_name , "r" , encoding = "utf-8" )
46
- except :
47
- print ("Error: File not found" )
48
- sys .exit ()
49
- excel_row = 1
50
- excel_column = 1
51
-
52
- for lines in file :
53
-
54
- lines = lines [:- 1 ]
55
- lines = lines .split (sep )
56
-
57
- for dat in lines :
58
-
59
- sheet .cell (excel_row , excel_column ).value = dat
60
-
61
- excel_column += 1
62
-
63
- excel_column = 1
64
- excel_row += 1
65
-
66
-
67
- workbook .save (ename )
68
- file .close ()
21
+ with open (csv_name , "r" , encoding = "utf-8" ) as file :
22
+ excel_row = 1
23
+ for line in file :
24
+ data = line .strip ().split (sep )
25
+ excel_column = 1
26
+ for value in data :
27
+ sheet .cell (row = excel_row , column = excel_column , value = value )
28
+ excel_column += 1
29
+ excel_row += 1
30
+
31
+ # Save the Excel file
32
+ workbook .save (excel_name )
33
+
34
+ except FileNotFoundError :
35
+ print ("Error: The CSV file was not found." )
36
+ except Exception as e :
37
+ print (f"An error occurred: { e } " )
0 commit comments