读写Excel,  写入excel指定位置

// 添加引用->Com->Microsoft Excel 12.0 Ojbect Library
using Excel = Microsoft.Office.Interop.Excel;


string excelPath = @"C:\Documents and Settings\ch\Desktop\transaction.xls";

// 创建一个新Excel的Application
Excel.Application app = new Excel.ApplicationClass();

// 设置界面是否可见
app.Visible = false;

// 获取工作簿对象:workbook
Excel.Workbook book = app.Workbooks.Open(excelPath, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);

// 新建工作簿
// book = app.Workbooks.Add(System.Type.Missing);

// 操作指定的工作表:sheet
Excel.Worksheet sheet = (Excel.Worksheet)book.Sheets[1];


// 或者获取默认的工作表
sheet = (Excel.Worksheet)book.ActiveSheet;

// 获取指定单元格的内容
//Excel.Range range = sheet.get_Range("C7", System.Type.Missing);
// txtContent.Text = range.Value2.ToString();

// 写数据到单元格
Excel.Range newRange = sheet.get_Range("C6", System.Type.Missing);
newRange.Value2 = "Hello World!";
//newRange.Interior.ColorIndex = 6; //设置Range的背景色

// 自动填充
newRange.EntireColumn.AutoFit();

sheet = null;
book.Save();
book.Close(sheet, excelPath, System.Type.Missing);
app.Quit();

System.GC.Collect();
在pandas中,我们可以使用`pandas.DataFrame.to_excel`方法将DataFrame写入Excel文件。但是,该方法默认会将DataFrame写入Excel文件的第一个空白工作表的左上角。如果我们想要将DataFrame写入Excel文件的指定位置,可以通过使用第三方库`openpyxl`来实现。 首先,我们需要在代码中导入`openpyxl`库。然后,我们可以通过创建一个ExcelWriter对象来指定DataFrame写入位置。 下面是一个使用`openpyxl`库将DataFrame写入Excel文件指定位置的示例代码: ```python import pandas as pd from openpyxl import load_workbook # 创建一个DataFrame df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) # 要写入Excel文件路径 file_path = 'example.xlsx' # 创建一个ExcelWriter对象,并加载Excel文件 writer = pd.ExcelWriter(file_path, engine='openpyxl') writer.book = load_workbook(file_path) # 指定DataFrame写入的起始位置 startrow = 2 startcol = 2 # 将DataFrame写入指定位置 df.to_excel(writer, sheet_name='Sheet1', startrow=startrow-1, startcol=startcol-1, index=False) # 保存Excel文件 writer.save() ``` 在上面的代码中,我们先创建一个DataFrame,并且指定了要写入Excel文件的路径。然后,通过创建一个ExcelWriter对象,并使用`load_workbook`方法加载已有的Excel文件。接下来,我们通过指定`startrow`和`startcol`的值来确定DataFrame写入的起始位置。最后,我们调用`to_excel`方法将DataFrame写入指定位置,并通过调用`save`方法保存Excel文件。 需要注意的是,这里的`startrow`和`startcol`的值是从1开始的。所以在代码中我们需要将实际的行数和列数减1来适应pandas的索引方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值