我有一个名为“Money”的数据库和一个表,我想把它导出到excel(.csv)。但是我不知道如何导出它,请帮助我:(
这是“comsumer”的结构:
public static final String DATABASE_KhoanChi = "CREATE TABLE "
+ KhoanChiTable + "(" + colkcID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + mathloaichi
+ " TEXT, " + colsotienkc + " Integer, " + colngaychi
+ " Date NOT NULL,FOREIGN KEY (" + mathloaichi + ") REFERENCES "
+ TheloaichiTable + " (" + coltlcID + "));";
答案 0 :(得分:1)
答案 1 :(得分:0)
在SO上已经讨论过太多次了。简单的搜索可以为您提供完整的解决方案。
正如所讨论的here,您只需要使用游标迭代值并将逗号分隔值写入文件。如果您有多行,只需遍历它们,构建新的dataString
并执行out.write(dataString)
。
String columnString = "\"Col1\",\"Col2\",\"Col3\",\"Col4\"";
String dataString = "\"" + var1 +"\",\"" + var2 + "\",\"" + var3 + "\",\"" + var4+ "\"";
String combinedString = columnString + "\n" + dataString;
File file = null;
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
File dir = new File (root.getAbsolutePath() + "/PersonData");
dir.mkdirs();
file = new File(dir, "Data.csv");
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
out.write(combinedString.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
此外,如果您要写入外部存储空间,请不要忘记清单中的权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
答案 2 :(得分:0)
您可以使用以下python程序来这样做:
import os, fnmatch
import sqlite3
import pandas as pd
#creates a directory without throwing an error
def create_dir(dir):
if not os.path.exists(dir):
os.makedirs(dir)
print("Created Directory : ", dir)
else:
print("Directory already existed : ", dir)
return dir
#finds files in a directory corresponding to a regex query
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
#convert sqlite databases(.db,.sqlite) to pandas dataframe(excel with each table as a different sheet or individual csv sheets)
def save_db(dbpath=None,excel_path=None,csv_path=None,extension="*.sqlite",csvs=True,excels=True):
if (excels==False and csvs==False):
print("Atleast one of the parameters need to be true: csvs or excels")
return -1
#little code to find files by extension
if dbpath==None:
files=find(extension,os.getcwd())
if len(files)>1:
print("Multiple files found! Selecting the first one found!")
print("To locate your file, set dbpath=<yourpath>")
dbpath = find(extension,os.getcwd())[0] if dbpath==None else dbpath
print("Reading database file from location :",dbpath)
#path handling
external_folder,base_name=os.path.split(os.path.abspath(dbpath))
file_name=os.path.splitext(base_name)[0] #firstname without .
exten=os.path.splitext(base_name)[-1] #.file_extension
internal_folder="Saved_Dataframes_"+file_name
main_path=os.path.join(external_folder,internal_folder)
create_dir(main_path)
excel_path=os.path.join(main_path,"Excel_Multiple_Sheets.xlsx") if excel_path==None else excel_path
csv_path=main_path if csv_path==None else csv_path
db = sqlite3.connect(dbpath)
cursor = db.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
print(len(tables),"Tables found :")
if excels==True:
#for writing to excel(xlsx) we will be needing this!
try:
import XlsxWriter
except ModuleNotFoundError:
!pip install XlsxWriter
if (excels==True and csvs==True):
writer = pd.ExcelWriter(excel_path, engine='xlsxwriter')
i=0
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
i+=1
print("Parsing Excel Sheet ",i," : ",table_name)
table.to_excel(writer, sheet_name=table_name, index=False)
print("Parsing CSV File ",i," : ",table_name)
table.to_csv(os.path.join(csv_path,table_name + '.csv'), index_label='index')
writer.save()
elif excels==True:
writer = pd.ExcelWriter(excel_path, engine='xlsxwriter')
i=0
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
i+=1
print("Parsing Excel Sheet ",i," : ",table_name)
table.to_excel(writer, sheet_name=table_name, index=False)
writer.save()
elif csvs==True:
i=0
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
i+=1
print("Parsing CSV File ",i," : ",table_name)
table.to_csv(os.path.join(csv_path,table_name + '.csv'), index_label='index')
cursor.close()
db.close()
return 0
save_db();
答案 3 :(得分:-2)
使用SQLLiteManager可以导出