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);
}
}
}