如何使用c#将文本框值写入Excel工作表?
问题描述:
如何使用c#将文本框值写入Excel工作表?我想通过选择它们将这些数据输入到单元格。请帮助我。
how to write text box values to an excel sheet using c#?i want to enter those data to cells by selecting them.please help me.
答
hi ,
你可以试试这个:
首先你必须导入Microsoft.Office.Core和Microsoft.Office.Interop.Excel COM引用。
第二名:
Can you try this:
First you must import "Microsoft.Office.Core" and "Microsoft.Office.Interop.Excel" COM references.
Second:
public void WriteToExcel()
{
string myPath = @"C:\Excel.xls"; // this must be full path.
FileInfo fi = new FileInfo(myPath);
if (!fi.Exists)
{
Console.Out.WriteLine("file doesn't exists!");
}
else
{
var excelApp = new Microsoft.Office.Interop.Excel.Application();
var workbook = excelApp.Workbooks.Open(myPath);
Worksheet worksheet = workbook.ActiveSheet as Worksheet;
Microsoft.Office.Interop.Excel.Range range = worksheet.Cells[1,1] as Range;
range.Value2 = "5";
//excelApp.Visible = true;
workbook.Save();
workbook.Close();
}
}
我希望这会有所帮助。
问候
Jegan
I hope this helps.
Regards
Jegan
看看这里:
CSpreadSheet - A Class读取和写入Excel和文本分隔的电子表格 [ ^ ]
您可以使用此C#Excel [ ^ ]库,但它也是一个像Microsoft Excel这样的商业API,它在我的项目中运行良好,希望你好运:
You can try below code by using this C# Excel[^]library, but it is also a commercial api like Microsoft Excel,it works fine in my project,hope you goodluck:
namespace textboxtoexcel
{
public partial class Form1 : Form
{
private bool stop = false;
private Workbook workbook = null;
private Worksheet worksheet = null;
private int rowIndex = 0;
private String fileName = null;
public Form1()
{
InitializeComponent();
}
private void labelSize_TextChanged(object sender, EventArgs e)
{
if (stop)
{
return;
}
String no = String.Format("No. {0}", rowIndex);
rowIndex++;
worksheet[rowIndex, 1].Text = no;
worksheet[rowIndex, 2].Text = this.labelSize.Text;
}
private void InitWorkbook()
{
workbook = new Workbook();
workbook.CreateEmptySheets(1);
worksheet = workbook.Worksheets[0];
worksheet.Name = "image size";
worksheet.Range[1, 1].Text = "No";
worksheet.Range[1, 2].Text = "Size Data";
rowIndex = 1;
fileName = String.Format("image-size-{0}.xls", Guid.NewGuid());
}
private void btnDemoStart_Click(object sender, EventArgs e)
{
this.btnOpenExcel.Enabled = false;
this.stop = false;
this.InitWorkbook();
Random random = new Random();
new Thread(() =>
{
while(!this.stop)
{
int width = random.Next(1024);
int height = random.Next(1024);
this.Invoke(new Action(() =>
{
this.labelSize.Text = String.Format("{0}, {1}", width, height);
}));
Thread.Sleep(1000);
}
}).Start();
}
private void btnDemoStop_Click(object sender, EventArgs e)
{
this.stop = true;
this.btnOpenExcel.Enabled = true;
this.workbook.SaveToFile(fileName);
}
private void btnOpenExcel_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(fileName);
}
}
}