Ошибка при преобразовании Excel в таблицу - PullRequest
0 голосов
/ 30 марта 2020

Я только начал изучать Python, и теперь я пытаюсь интегрировать это со своими знаниями ГИС. Как следует из заголовка, я пытаюсь преобразовать лист Excel в таблицу, но продолжаю получать ошибки, одна из которых совершенно не поддается расшифровке, а другая, кажется, предполагает, что мой файл не существует, что, я знаю, неверно поскольку я скопировал его местоположение непосредственно из его свойств.

Вот скриншот моей среды. Пожалуйста, помогите, если вы можете и спасибо заранее.

Окружающая среда / Ошибка

Ответы [ 2 ]

0 голосов
/ 02 апреля 2020

Arcpy использует следующий синтаксис для преобразования таблиц базы геоданных в Excel enter image description here

Это просто.

Пример

Таблицы Excel нельзя хранить в базе геоданных. Наиболее разумно хранить их в корневой папке, в которой находится база геоданных с таблицей. Скажем, я хочу преобразовать таблицу this geodatabase, приведенную ниже, в Excel и сохранить ее в папке root или в папке, в которой находится база геоданных.

Я сделаю go следующим образом : Я поставил объяснения после #.

import arcpy
import os
from datetime import datetime, date, time

# Set environment settings
in_table= r"C:\working\Sunderwood\Network Analyst\MarchDistances\Centroid.gdb\SunderwoodFirstArcpyTable"

#os.path.basename(in_table)

out_xls= os.path.basename(in_table)+ datetime.now().strftime('%Y%m%d') # Here

#os.path.basename(in_table)- Gives the base name of pathname. In this case, it returns  the name table
# + is used in python to concatenate
# datetime.now()- gives todays date
# Converts todays date into a string in the format YYYMMDD
# Please add all the above statements and you notice you have a new file name which is the table you input plus todays date


#os.path.dirname() method in Python is used to get the directory name from the specified path
geodatabase = os.path.dirname(in_table)
# In this case, os.path.dirname(in_table)  gives us the geodatabase


# The The join() method takes all items in an iterable and joins them into one string
SaveInFolder= "\\".join(geodatabase.split('\\')[:-1])

# This case, I tell python take \ and join on the primary directory above which I have called geodatabase. However, I tell it to remove some characters. I will explain the split below.

# I use split method. The split() method splits a string into a list
#In the case above it splits into  ['W:\\working\\Sunderwood\\Network', 'Analyst\\MarchDistances\\Centroid.gdb']. However, that is not what I want. I want to remove "\\Centroid.gdb" so that I remain with the follwoing path ['W:\\working\\Sunderwood\\Network', 'Analyst\\MarchDistances']

#Before I tell arcpy to save, I have to specify the workspace in which it will save. So I now make my environment the SaveInFolder
arcpy.env.workspace =SaveInFolder

## Now I have to tell arcpy what I will call my newtable. I use os.path.join.This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component
newtable = os.path.join(arcpy.env.workspace, out_xls)

#In the above case it will give me "W:\working\Sunderwood\Network Analyst\MarchDistances\SunderwoodFirstArcpyTable20200402"

# You notice the newtable does not have an excel extension. I resort to + to concatenate .xls onto my path and make it "W:\working\Sunderwood\Network Analyst\MarchDistances\SunderwoodFirstArcpyTable20200402.xls"

table= newtable+".xls"

#Finally, I call the arcpy method and feed it with the required variables
# Execute TableToExcel
arcpy.TableToExcel_conversion(in_table, table)
print (table + "  " + " is now available")
0 голосов
/ 31 марта 2020

Проще говоря, вы помещаете каталог рабочей области в переменную имени файла, поэтому, когда arcpy обрабатывает его, он пытается получить доступ к файлу, который не существует, в неизвестной рабочей области.

Попробуйте это.

arcpy.env.workspace = "J:\egis_work\dpcd\projects\SHARITA\Python\"
arcpy.ExcelToTable_conversion("Exceltest.xlsx", "Bookstorestable", "Sheet1")
...