在處理電子表格時,可能常常須要在工做表中插入或刪除行和列。所以,本文將介紹如何以編程方式處理工做表中的行和列。特別是,將學習如何使用Python在Excel工做表中插入或刪除單行或多行和多列。編程
使用Python在工做表中插入行
使用Python在Excel工做表中插入列
使用Python刪除Excel工做表中的行
使用Python刪除Excel工做表中的列
爲了在Excel工做表中插入或刪除行和列,咱們將Aspose.Cells for Python via Java它是一個功能強大的電子表格處理API,可爲Excel自動化提供多種功能。你能夠下載Aspose.Cells for Python via Java使用。app
使用Python在Excel工做表中插入行
如下是使用Python在Excel工做表中插入行的步驟。ide
首先,使用Workbook類加載Excel文件。
使用Workbook.getWorksheets().get(index)方法經過索引訪問所需的工做表。
使用Worksheet.getCells().insertRows(rowIndex,totalRows)方法插入行,其中第一個參數是行索引,第二個參數是要插入的行數。
最後,使用Workbook.save(string)方法保存更新的文件。
下面的代碼示例演示如何使用Python在Excel工做表中插入行。學習
workbook = self.Workbook(「Book1.xls」)spa
Access the first worksheet in the Excel fileworksheet = workbook.getWorksheets().get(0)excel
Insert a row into the worksheet at 3rd positionworksheet.getCells(www.weysale.com).insertRows(2,1)orm
Save the modified Excel file in default (that is Excel 2003) formatworkbook.save(「Insert Row.xls」)
print 「Insert Row Successfully.」
使用Python在Excel工做表中插入列
如下是使用Python在Excel工做表中插入列的步驟。索引
首先,使用Workbook類加載Excel文件。
使用Workbook.getWorksheets().get(index)方法經過索引訪問所需的工做表。
使用Worksheet.getCells().insertColumns(columnIndex,totalColumns)方法插入列,其中第一個參數是列索引,第二個參數是要插入的列數。
最後,使用Workbook.save(string)方法保存更新的文件。
下面的代碼示例演示如何使用Python在Excel工做表中插入列。get
workbook = self.Workbook(‘Book1.xls’)string
Access the first worksheet in the Excel fileworksheet = workbook.getWorksheets(www.jqmms.com).get(0)
Insert a column into the worksheet at 2nd positionworksheet.getCells().insertColumns(1,1)
Save the modified Excel file in default (that is Excel 2003) formatworkbook.save(「Insert Column.xls」)
print 「Insert Column Successfully.」
使用Python在Excel中刪除行
如下是使用Python從Excel工做表中刪除行的步驟。
首先,使用Workbook類加載Excel文件。
使用Workbook.getWorksheets().get(index)方法經過索引訪問所需的工做表。
使用Worksheet.getCells().deleteRows(rowIndex,totalRows)方法刪除行,其中第一個參數是行索引,第二個參數是要刪除的行數。
最後,使用Workbook.save(string)方法保存更新的文件。
如下代碼示例顯示瞭如何從Python中的Excel工做表中刪除行。
workbook = self.Workbook(「Book1.xls」)
Access the first worksheet in the Excel fileworksheet = workbook.getWorksheets().get(0)
Delete 10 rows from the worksheet starting from 3rd rowworksheet.getCells().deleteRows(2,10,True)
Save the modified Excel file in default (that is Excel 2003) formatworkbook.save(「Insert Row.xls」)
print 「Insert Row Successfully.」
使用Python在Excel中刪除列
如下是使用Python從Excel工做表中刪除列的步驟。
首先,使用Workbook類加載Excel文件。
使用Workbook.getWorksheets().get(index)方法經過索引訪問所需的工做表。
使用Worksheet.getCells().insertColumns(columnIndex,totalColumns,updateReference)方法刪除列。第一個參數是列索引,第二個參數是要刪除的列數,第三個參數指示是否須要在其餘工做表中更新引用。
最後,使用Workbook.save(string)方法保存更新的文件。
下面的代碼示例演示如何使用Python從Excel工做表中刪除列。
workbook = self.Workbook(‘Book1.xls’)
Access the first worksheet in the Excel fileworksheet = workbook.getWorksheets().get(0)
Delete a column from the worksheet at 2nd positionworksheet.getCells().deleteColumns(1,1,True)
Save the modified Excel file in default (that is Excel 2003) formatworkbook.save(「Insert Column.xls」)print 「Insert Column Successfully.」