My task:
Get data from a website and write it to an Excel file with real time (0.5 - 1s use Microsoft.Office.Interop.Excel)
While the program write data to the Excel file, I want to open this file with (Excel or something like it) to see the data, chart...
So how can I read and write the Excel file in the same time? Or can I use the other way?
void ExportToExcel() {
try
{
SaveFileDialog svg = new SaveFileDialog();
using (FileStream stream = new FileStream(svg.FileName + ".xlsx", FileMode.Create))
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
int StartCol = 1;
int StartRow = 1;
int j = 0, i = 0;
//Write Headers
for (j = 0; j < dataGridView1.Columns.Count; j++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
myRange.Value2 = dataGridView1.Columns[j].HeaderText;
}
StartRow++;
//Write datagridview content
for (i = 0; i < dataGridView1.Rows.Count; i++)
{
for (j = 0; j < dataGridView1.Columns.Count; j++)
{
try
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
myRange.Value2 = dataGridView1[j, i].Value == null ? "" : dataGridView1[j, i].Value.ToString();
}
catch
{
;
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.