读写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();

你可能感兴趣的:(c#)