如何使用python将现有的.xlsx粘贴数据框打开到指定的电子表格和位置,而无需清除其他选项卡和值?

时间:2019-05-20 12:49:11

标签: python excel openpyxl

我想从.csv文件复制一个数据帧,然后将其粘贴到指定工作表和指定位置的现有.xls文件中。

此代码将数据帧写入现有的excel文件,但是它将完全覆盖该文件。该工作簿也包含其他选项卡。 结果是将其复制并粘贴到指定的位置, 但是其他标签和单元格值也被清除了。

import os
import pandas as pd
import datetime
import csv
import xlsxwriter

from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.chart import LineChart,Reference 

from win32com.client import Dispatch
import os

from pandas import ExcelWriter

xl = Dispatch("Excel.Application")
xl.Visible = True

#record start time
currentDT_start =datetime.datetime.now()

# Read index data from .csv
index_file=r"file\name\.."
analysis_file=r"file\name.."

py_index_file=index_file.replace('\\','\\\\')
py_analysis_file=analysis_file.replace('\\','\\\\')

#copying 
index = pd.read_csv(py_index_file,skiprows=1)
#print(index.head())



#this code write the dataframe to the existing excel file, but it overwrite the file completely. the workbook consists of other tabs too.
# the outcome was it copied and pasted to specified location
# but other tabs and cells values got wiped out too.

writer=ExcelWriter(py_analysis_file)
index.to_excel(writer,'Indexes',startrow=1)
writer.save()


currentDT_end=datetime.datetime.now()

print('Code started on ' + currentDT_start.strftime("%Y-%m-%d %H:%M:%S") + ' !')
print('Code completed on ' + currentDT_end.strftime("%Y-%m-%d %H:%M:%S") + ' !')

1 个答案:

答案 0 :(得分:0)

我相信您根据docs使用的library(tidyverse) df %>% transmute(Sum = reduce(.[-1], `+`)) %>% mutate(Sum = factor(recode(Sum, `3` = 'AllTrue', `0`= 'AllFalse', .default = 'Mixed'), levels = c("AllTrue", 'AllFalse', 'Mixed'))) %>% count(Sum, .drop = FALSE) # A tibble: 3 x 2 # Sum n # <fct> <int> #1 AllTrue 9 #2 AllFalse 0 #3 Mixed 3 格式不正确。您需要传入[{ "ProductName": "Test Product 1", "QuantityPerUnit": "100" }, { "ProductName": "Test Product 2", "QuantityPerUnit": "10" }, { "ProductName": "Test Product 3", "QuantityPerUnit": "25" }] 作为第二个参数。

请尝试以下操作:

angular.module("angularApp", [])
    .controller("ProductController", function ($scope,$http) {   
        $http.get("dummy.json").then(function(response) {
          console.log("Json",response.data);
          $scope.products = response.data;
        });
});