簡體   English   中英

將 PDF 轉換為 XLS

[英]Convert PDF to XLS

我想將 PDF 文件轉換為 CSV 或 XLS。 我嘗試通過使用 python tabula 來做到這一點:

#!/bin/bash
#!/usr/bin/env python3
import tabula

# Read pdf into list of DataFrame
df = tabula.read_pdf("File1.pdf", pages='all')

# convert PDF into CSV file
tabula.convert_into("File1.pdf", "File1.csv", output_format="csv", pages='all')

# convert all PDFs in a directory
#tabula.convert_into_by_batch("input_directory", output_format='csv', pages='all')

雖然python腳本將PDF轉換為CSV,但十進制不正確。

例如 1.25 僅顯示為 1.2。

所以我想將小數位增加到兩位,以便在轉換后的 CSV 文件中獲得正確的數字。

有人可以幫我嗎?

謝謝你。

根據需要,我們需要調整tabula上的參數,以便數據導入有意義。 我在評論中建議的參數只是一個例子。 要使列從 x 軸開始,我們需要使用 acrobat 的付費版本或帶有一些軌跡。

所以代碼會像

導入和設置

import tabula
import pandas as pd
pdf_file='file1.pdf'
column_names=['Product','Batch No','Machin No','Time','Date','Drum/Bag No','Tare Wt.kg','Gross Wt.kg',
              'Net Wt.kg','Blender','Remarks','Operator']

由於頁面格式不同,需要單獨處理。 並進行一些清理,例如刪除不需要的列或某個值后的數據(請參閱第 2 頁處理)

# Page 1 processing
df1 = tabula.read_pdf(pdf_file, pages=1,area=(95,20, 800, 840),columns=[93,180,220,252,310,315,333,367,
                                                                      410,450,480,520]
                     ,pandas_options={'header': None}) #(top,left,bottom,right)
df1[0]=df1[0].drop(columns=5)
df1[0].columns=column_names
#df1[0].head(2)
# Page 2 processing
df2 = tabula.read_pdf(pdf_file, pages=2,area=(10,20, 800, 840),columns=[93,180,220,252,310,315,330,370,
                                                                      410,450,480,520]
                     ,pandas_options={'header': None}) #(top,left,bottom,right)

row_with_Sta = df2[0][df2[0][0] == 'Sta'].index.tolist()[0]
df2[0] = df2[0].iloc[:row_with_Sta]
df2[0]=df2[0].drop(columns=5)
df2[0].columns=column_names
#df2[0].head(2)
result = pd.concat([df1[0],df2[0]]) # concate both the pages and then write to CSV
result.to_csv("result.csv")

筆記: 請測試代碼,因為我只有一定程度的驗證:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM