I've scoured the net for days to find a working example of how to
use csharp to open an excel file and put a value in a cell. Its dead easy in VB6, VBA,
vb.net but not csharp.
I've managed to get this working but I'm sure its not the easiest way of doing this.
Its the part where I assign the range to Range one that looks well dodgy.
Is there any better way of doing this?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
namespace Exceltest3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int ColCount;
int RowCount;
Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks theWorkbooks;
theWorkbooks = ExcelObj.Workbooks;
Microsoft.Office.Interop.Excel.Workbook theWorkbook;
theWorkbook = theWorkbooks.Open("c:\\test\\input1.xls", 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindow s, "\t", false, false, 0, true,false, false);
Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.g et_Item(1);
ColCount = worksheet.UsedRange.Columns.Count;
RowCount = worksheet.UsedRange.Rows.Count;
//Is it really necessary to use worksheet.get_Range to get this
//to work or have I taken the wrong approach.
Microsoft.Office.Interop.Excel.Range Range1 = worksheet.get_Range("a1","a1");
Range1.Cells[1, 1] = "11";
}
}
}