在多个程序访问的Excel文件中读写

时间:2017-12-10 19:05:41

标签: c# .net excel

我的任务: 从网站获取数据并实时将其写入Excel文件(0.5 - 1s使用Microsoft.Office.Interop.Excel) 当程序将数据写入Excel文件时,我想用(Excel或类似的东西)打开这个文件来查看数据,图表...... 那么如何在同一时间读写Excel文件呢?或者我可以使用其他方式吗?

1 个答案:

答案 0 :(得分:1)

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

    }