如何关闭OleDB连接,以便我可以使用EPPlus删除Excel数据

时间:2016-12-28 03:12:07

标签: c# excel

在使用oledb插入数据后删除Excel数据时,我遇到了一些问题。错误说我的文件正由另一个进程使用。我已关闭连接但错误仍然存​​在。任何人都可以帮我解决这个问题吗?

string tampungsementara = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Proyek Alfon\JadwalPengisianATM\Tampung Data Sementara.xlsx;Extended Properties='Excel 12.0 xml;HDR=YES';";


    private void MoveToScheduleBtn_Click(object sender, EventArgs e)
            {
                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += new DoWorkEventHandler(PindahKeJadwalIsiBW_DoWork);
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(PindahKeJadwalIsiBW_RunWorkerCompleted);

                try
                {
                    bw.RunWorkerAsync();
                }
                catch
                {
                    MessageBox.Show("File gagal dipindah !");
                }
            }

    private void PindahKeJadwalIsiBW_DoWork(object sender, DoWorkEventArgs e)
    {
        foreach (DataGridViewRow item in ReviewGV.Rows)
        {
            if (Convert.ToBoolean(item.Cells[0].Value) == true) 
            {
                using (OleDbConnection kon = new OleDbConnection(tampungsementara))
                {
                    string com = "INSERT INTO [Schedule$] ([WSID], [Lokasi]) VALUES (wsid, lokasi)";
                    kon.Open();

                    using (OleDbCommand command = new OleDbCommand(com, kon))
                    {
                        command.Parameters.AddWithValue("wsid", item.Cells[1].Value);
                        command.Parameters.AddWithValue("lokasi", item.Cells[2].Value);

                        command.ExecuteNonQuery();

                        kon.Close();
                        //command.Dispose();

                    }
                }

                using (ExcelPackage package = new ExcelPackage(new FileInfo(filetampungsementara))) //error here
                {
                    ExcelWorksheet unsche = package.Workbook.Worksheets["Unschedule"];
                    int h = unsche.Dimension.End.Row;
                    textBox1.Text = h.ToString();
                }
            }
        }
    }

private void PindahKeJadwalIsiBW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("Data berhasil dipindah ke Jadwal Pengisian !");

            TampilJadwal();
            TampilDataLain();
        }

0 个答案:

没有答案