2016-02-16 14 views
11

Ad esempio, leggo il file excel in DataFrame con 2 colonne (id e URL). Gli URL nei file di input sono come il testo (senza collegamenti ipertestuali):Come salvare in * .xlsx lungo URL nella cella usando Pandas

input_f = pd.read_excel("input.xlsx") 

Guarda cosa all'interno di questa dataframe - tutto è stato letto con successo, tutti gli URL sono ok in input_f. Dopo di che quando non voglio salvare questo file per_excel

input_f.to_excel("output.xlsx", index=False) 

Ho avvertito.

Path \ worksheet.py: 836: UserWarning: Ignorando URL 'http: // qui URL lungo' con link o posizione/ancoraggio> 255 caratteri, poiché supera il limite di Excel per gli URL force_unicode (url))

E nelle celle output.xlsx con URL lungo erano vuoti e gli URL diventano collegamenti ipertestuali.

Come risolvere il problema?

risposta

19

È possibile creare un oggetto ExcelWriter con l'opzione di non convertire le stringhe a URL:

writer = pandas.ExcelWriter(r'file.xlsx', engine='xlsxwriter',options={'strings_to_urls': False}) 
df.to_excel(writer) 
writer.close() 
3

Ho provato da solo e ho avuto lo stesso problema. Si potrebbe provare a creare un file csv temporaneo e quindi utilizzare xlsxwriter per creare un file excel. Al termine, eliminare il file tmp. xlsxwriter ha un metodo write_string che sovrascrive l'hyperlinking automatico che fa excel. Questo ha funzionato per me.

import pandas as pd 
import csv 
import os 
from xlsxwriter.workbook import Workbook 
inData = "C:/Users/martbar/Desktop/test.xlsx" 
tmp = "C:/Users/martbar/Desktop/tmp.csv" 
exFile = "C:/Users/martbar/Desktop/output.xlsx" 

#read in data 
df = pd.read_excel(inData) 

#send to csv 
df.to_csv(tmp, index=False) 

#convert to excel 
workbook = Workbook(exFile) 
worksheet = workbook.add_worksheet() 
with open(tmp, 'r') as f: 
    reader = csv.reader(f) 
    for r, row in enumerate(reader): 
     for c, col in enumerate(row): 
      #if you use write instead of write_string you will get the error 
      worksheet.write_string(r, c, col) 
workbook.close() 

#delete tmp file 
os.remove(tmp)