[英]Reading and writing in Excel file with multiple programs accessing
我的任務:
從網站獲取數據並將其實時寫入Excel文件(使用Microsoft.Office.Interop.Excel的時間為0.5-1s)
當程序將數據寫入Excel文件時,我想使用(Excel或類似的東西)打開該文件以查看數據,圖表...
那么,如何同時讀寫Excel文件呢? 還是可以使用其他方式?
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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.