-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimport_excel.py
296 lines (252 loc) · 10.2 KB
/
import_excel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import pandas as pd
import pymysql
import os
import sys
def process_partners_data(excel_path):
"""Process the Partners Excel file data"""
try:
# Read Excel file
df = pd.read_excel(excel_path)
# Print column names for debugging
print("Available columns in partners file:", df.columns.tolist())
# Map the Excel columns to the database columns
column_mapping = {
'Наименование партнера': 'name',
'Тип партнера': 'type',
'ИНН': 'inn',
'Рейтинг': 'rating',
'Город': 'city',
'Улица': 'street',
'Дом': 'building',
'Фамилия директора': 'director_lastname',
'Имя директора': 'director_firstname',
'Отчество директора': 'director_middlename',
'Телефон партнера': 'phone',
'Электронная почта партнера': 'email'
}
# Rename columns
df = df.rename(columns=column_mapping)
# Check required columns
required_columns = ['name', 'inn']
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
print(f"Missing required columns in partners file: {missing_columns}")
return None
# Clean data (remove empty rows, etc.)
df = df.dropna(subset=['name', 'inn']) # Require at least name and INN
return df
except Exception as e:
print(f"Error processing Partners data: {str(e)}")
return None
def process_products_data(excel_path):
"""Process the Partner_products Excel file data"""
try:
# Read Excel file
df = pd.read_excel(excel_path)
# Print column names for debugging
print("Available columns in products file:", df.columns.tolist())
# Map Excel columns to database columns
column_mapping = {
'Наименование партнера': 'partner_id', # Will need conversion to ID
'Продукция': 'product_name',
'Количество продукции': 'count_product', # Using quantity field correctly
'Дата продажи': 'date_sale' # Using date field
}
# Rename columns
df = df.rename(columns=column_mapping)
# Generate a product code
df['product_code'] = df['product_name'].str.slice(0, 10).str.upper().str.replace(' ', '_')
# Add default price if not present
if 'price' not in df.columns:
df['price'] = 0 # Default price, will be updated later
# Check required columns
required_columns = ['partner_id', 'product_name', 'count_product', 'date_sale']
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
print(f"Missing required columns in products file: {missing_columns}")
return None
return df
except Exception as e:
print(f"Error processing Products data: {str(e)}")
return None
def get_partner_id_map(host, port, user, password, db_name):
"""Get a mapping of partner names to IDs"""
try:
conn = pymysql.connect(
host=host,
port=port,
user=user,
password=password,
database=db_name
)
cursor = conn.cursor()
cursor.execute("SELECT id, name FROM Partners")
rows = cursor.fetchall()
conn.close()
# Create a mapping of name -> id
return {row[1]: row[0] for row in rows}
except Exception as e:
print(f"Error getting partner ID map: {str(e)}")
return {}
def import_to_database(host, port, user, password, db_name):
"""Import processed Excel data to MySQL database"""
try:
# Process Excel files
partners_df = process_partners_data("Ресурсы/Partners_import.xlsx")
if partners_df is None:
return False
# Connect to database
conn = pymysql.connect(
host=host,
port=port,
user=user,
password=password,
database=db_name
)
cursor = conn.cursor()
# First, import Partners data
print("Importing partner data...")
for _, row in partners_df.iterrows():
# Create SQL query with proper escaping to prevent SQL injection
query = """
INSERT INTO Partners (
name, type, city, street, building,
director_lastname, director_firstname, director_middlename,
phone, email, inn, rating
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
# Extract values from dataframe
values = (
row.get('name', ''),
row.get('type', 'ООО'),
row.get('city', ''),
row.get('street', ''),
row.get('building', ''),
row.get('director_lastname', ''),
row.get('director_firstname', ''),
row.get('director_middlename', ''),
row.get('phone', ''),
row.get('email', ''),
row.get('inn', ''),
int(row.get('rating', 0))
)
# Execute query
cursor.execute(query, values)
# Commit changes to save partner data
conn.commit()
print(f"Imported {len(partners_df)} partners successfully")
# Now get partner ID mapping
partner_id_map = get_partner_id_map(host, port, user, password, db_name)
# Now import Products data
products_df = process_products_data("Ресурсы/Partner_products_import.xlsx")
if products_df is None:
conn.close()
return False
print("Importing product data...")
imported_count = 0
for _, row in products_df.iterrows():
# Map partner name to partner_id
partner_name = row.get('partner_id')
if isinstance(partner_name, (int, float)):
# If it's already a number, use it directly
partner_id = int(partner_name)
else:
# Otherwise look up in the mapping
partner_id = partner_id_map.get(partner_name)
if not partner_id:
print(f"Warning: Could not find partner ID for '{partner_name}'")
continue
query = """
INSERT INTO Partner_products (
partner_id, product_name, product_code, price, count_product, date_sale
) VALUES (%s, %s, %s, %s, %s, %s)
"""
values = (
partner_id,
row.get('product_name', ''),
row.get('product_code', ''),
float(row.get('price', 0)),
int(row.get('count_product', 1)),
row.get('date_sale')
)
cursor.execute(query, values)
imported_count += 1
# Commit changes and close connection
conn.commit()
conn.close()
print(f"Imported {imported_count} products successfully")
print("Data imported successfully")
return True
except Exception as e:
print(f"Error importing data to database: {str(e)}")
return False
def create_database_and_tables(host, port, user, password, db_name):
"""Create the database and tables if they don't exist"""
try:
# Connect to MySQL server (without specifying database)
conn = pymysql.connect(
host=host,
port=port,
user=user,
password=password
)
cursor = conn.cursor()
# Create database if it doesn't exist
cursor.execute(f"CREATE DATABASE IF NOT EXISTS {db_name}")
# Switch to the database
cursor.execute(f"USE {db_name}")
# Create Partners table
cursor.execute("""
CREATE TABLE IF NOT EXISTS Partners (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
type VARCHAR(20) NOT NULL,
city VARCHAR(100),
street VARCHAR(100),
building VARCHAR(20),
director_lastname VARCHAR(50),
director_firstname VARCHAR(50),
director_middlename VARCHAR(50),
phone VARCHAR(20),
email VARCHAR(100),
inn VARCHAR(20) UNIQUE NOT NULL,
rating INT
)
""")
# Create Partner_products table with sales history fields
cursor.execute("""
CREATE TABLE IF NOT EXISTS Partner_products (
id INT AUTO_INCREMENT PRIMARY KEY,
partner_id INT NOT NULL,
product_name VARCHAR(100) NOT NULL,
product_code VARCHAR(50) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
count_product INT DEFAULT 1,
date_sale DATE,
FOREIGN KEY (partner_id) REFERENCES Partners(id) ON DELETE CASCADE
)
""")
conn.commit()
conn.close()
print("Database and tables created successfully")
return True
except Exception as e:
print(f"Error creating database and tables: {str(e)}")
return False
if __name__ == "__main__":
# Database connection parameters
host = "t1brime-dev.ru"
port = 3306
user = "toonbrime"
password = "Bebra228"
db_name = "CBO"
# First create database and tables if they don't exist
if create_database_and_tables(host, port, user, password, db_name):
# Then import data
success = import_to_database(host, port, user, password, db_name)
if success:
print("Excel data successfully imported to database")
else:
print("Failed to import Excel data")
else:
print("Failed to set up database structure")