Excel 寫檔

  • 2907
  • 0

使用C#開啟一個excel檔後寫資料

try
            {
                //應用程序
                Excel.Application App1 = new Excel.Application();
                //檔案
                Excel.Workbook WB1 = App1.Workbooks.Open(file_name.Text);
                //工作表
                Excel.Worksheet WS1 = new Excel.Worksheet();
                WS1 = WB1.Worksheets[2];

                //寫入表體資料
                object[,] arrBody = new object[dataGridView1.RowCount, 14];

                for (int i = 0; i < dataGridView1.RowCount - 1; i++)
                {
                    arrBody[i, 0] = "";
                    arrBody[i, 1] = "";
                    arrBody[i, 2] = "";
                    arrBody[i, 3] = "";
                    arrBody[i, 4] = "";
                    arrBody[i, 5] = "";
                    arrBody[i, 6] = "'" + dataGridView1[2, i].Value.ToString();
                    arrBody[i, 7] = "1";
                    arrBody[i, 8] = "PCE";
                    arrBody[i, 9] = dataGridView1[10, i].Value.ToString();
                    arrBody[i, 10] = "";
                    arrBody[i, 11] = "";
                    arrBody[i, 12] = dataGridView1[11, i].Value.ToString();
                    arrBody[i, 13] = dataGridView1[8, i].Value.ToString();

                    btn_Convert_SAP.Text = "Convert SAP " + (dataGridView1.RowCount - i - 2).ToString();
                    System.Windows.Forms.Application.DoEvents();
                }

                WS1.Range[WS1.Cells[2, 1], WS1.Cells[dataGridView1.RowCount, 14]].Value2 = arrBody;

                btn_Convert_SAP.Text = "Convert SAP";
                WB1.Save();

                WS1 = null;
                WB1.Close();
                WB1 = null;
                App1.Quit();
                App1 = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            MessageBox.Show("SAP BOM存檔完成!");