读写Excel,  写入excel指定位置

本文介绍如何使用C#及Microsoft.Office.Interop.Excel库来读取、写入并操作Excel文件,包括打开现有文件、写入数据到指定单元格、调整列宽等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 添加引用->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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值