Skip to content

Instantly share code, notes, and snippets.

@jmyzk
Last active June 15, 2023 08:10
Show Gist options
  • Save jmyzk/5c5229128b11ef3ec3ec4ac2383c5d15 to your computer and use it in GitHub Desktop.
Save jmyzk/5c5229128b11ef3ec3ec4ac2383c5d15 to your computer and use it in GitHub Desktop.
Import a CSV file with more than 10,000 and 10 columns to Smartsheet
import os
import smartsheet
import csv
# Uncomment and set your Smartsheet API access token
# access_token = 'YOUR_ACCESS_TOKEN'
# Initialize the Smartsheet client
client = smartsheet.Smartsheet(access_token)
def create_sheet_from_csv(csv_file, sheet_name=None, folder_id=None, primary_index=0, header_row_number=0):
# Load the CSV file
rows = []
with open(csv_file, 'r') as file:
reader = csv.reader(file)
for row in reader:
rows.append(row)
# Set the column names using the first row of the CSV
column_names = rows[header_row_number]
columns = []
index = 0
for name in column_names:
if index == primary_index:
primary_value = True
else:
primary_value = False
column = {
'title': name,
'primary': primary_value,
'type': 'TEXT_NUMBER'
}
columns.append(column)
index += 1
# Set the sheet name if not given
if sheet_name is None:
sheet_name = os.path.splitext(os.path.basename(csv_file))[0]
# Create the sheet
sheet_spec = smartsheet.models.Sheet({
'name': sheet_name,
'columns': columns
})
response = client.Folders.create_sheet_in_folder(folder_id, sheet_spec)
new_sheet = response.result
column_ids = [column.id for column in new_sheet.columns]
new_rows = []
row_number = 0
for row in rows:
if row_number>header_row_number:
new_row = smartsheet.models.Row()
new_row.to_top = True
for column_id, cell_value in zip(column_ids, row):
new_row.cells.append({
'column_id': column_id,
'value': cell_value
})
new_rows.append(new_row)
row_number+=1
# Add rows to the sheet
response = client.Sheets.add_rows(new_sheet.id, new_rows)
if response.message == "SUCCESS":
print(f"Successfully created a sheet with {len(new_rows)} rows.")
else:
print(f"Failed create a sheet with {response.error_count} rows.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment