I am using C# windows application for Excel data add/update. I had added Microsoft.Office.Interop.Excel
reference(Reference -> Right Click -> Add Reference -> COM -> Type Libraries -> Microsoft Excel 1X.0 Object Libraries). On my form, I have one panel control panel1
, one List-box lstSamples
and two button btnAddSample
, btnFormatWorksheet
.
My sample code is as below:
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public partial class Form1 : Form
{
Microsoft.Office.Interop.Excel.Application excelApp;
Workbook excelWorkBook;
Worksheet excelWorkSheet;
public Form1()
{
InitializeComponent();
LoadExcelFile();
}
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
private void LoadExcelFile()
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = true;
excelApp.ScreenUpdating = true;
excelApp.EnableAutoComplete = false;
excelWorkBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
IntPtr excelHwnd = new IntPtr(excelApp.Application.Hwnd);
SetParent(excelHwnd, panel1.Handle);
}
private void btnAddSample_Click(object sender, EventArgs e)
{
excelWorkSheet = (Worksheet)excelWorkBook.Worksheets.get_Item(1);
int lastUsedRow = excelWorkSheet.UsedRange.Rows.Count;
excelWorkSheet.Cells[lastUsedRow + 1, 1] = lstSamples.SelectedItem.ToString();
lstSamples.Items.Remove(lstSamples.SelectedItem);
}
private void btnFormatWorksheet_Click(object sender, EventArgs e)
{
Range chartRange;
excelWorkSheet = (Worksheet)excelWorkBook.Worksheets.get_Item(1);
chartRange = excelWorkSheet.get_Range("b2", "e9");
chartRange.BorderAround(XlLineStyle.xlContinuous,
XlBorderWeight.xlMedium, XlColorIndex.xlColorIndexAutomatic,
XlColorIndex.xlColorIndexAutomatic);
}
}
Please follow the steps as I mentioned 1. Run the application and add data in "A1" cell (Which is of string type) 2. Again add some data in "A2" cell and Press enter 3. Select one item from lstSamples
listbox and click on btnAddSample
(Result is like selected item will get added into "A3" cell 4. Try to modify "A1" or "A2" cell data. (Here lstSample
is having items of string type like Test1, Test2, Test3,....). If you are able to edit cells then click on btnFormatWorksheet
then try to edit any cell.
btnAddSample
button? – 41686d6564lstSamples
when you click the button? Does it get into the sheet successfully? Also, can you please elaborate on the "I'm not able to do the modification manually" part? Can you actually type in a cell or not? If not, what happens when you activate Excel and double click an empty cell? – 41686d6564