public partial class MyClass
{
private BackgroundWorker worker = null;
private Form frmProgress = null;
public MyClass()
{
InitializeComponent();
worker = new BackgroundWorker(); // 初始化
worker.WorkerReportsProgress = true; //报告进度更新
worker.WorkerSupportsCancellation = true; //可以异步取消
worker.DoWork += new DoWorkEventHandler(DoWorks); //在DoWorks()里定义异步要干的事
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerCompleted); //DoWorks完成后要做的事WorkerCompleted()
}
//主线程,点击按钮引发的事件
private void tsBtnExport_Click(object sender, EventArgs e)
{
OleDbConnection conExcel = new OleDbConnection(strConn);
try
{
OpenFileDialog openFile = new OpenFileDialog();//打开文件对话框。
openFile.Filter = ("Excel 文件(*.xls)|*.xls");//后缀名。
if (openFile.ShowDialog() == DialogResult.OK)
{
if (worker.IsBusy) worker.CancelAsync();
if (worker.CancellationPending) return;
ArrayList al = new ArrayList();
al.Add(openFile.FileName);
al.Add("Import");
worker.RunWorkerAsync(al);
ProgressShow();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conExcel.Close();
}
}
/// <summary>
/// 导入导出主要操作(后台线程)
/// </summary>
/// <param name="sender"></param>
/// <param name="e">异步过来的参数</param>
private void DoWorks(object sender, DoWorkEventArgs e)
{
if (e.Argument != null)
{
try
{
if (((ArrayList)(e.Argument))[1].ToString() == "Import")
{
string filename = ((ArrayList)(e.Argument))[0].ToString();
string strSql = "select distinct officeid from tbl_member";
DataSet ds = SqlHelper.ExecuteSqlReturnDs(strConn, strSql);
//List<string> liStr = new List<string>();
StringBuilder sbList = new StringBuilder("");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//liStr.Add(ds.Tables[0].Rows[i]["distinct"].ToString());
sbList.Append("'" + ds.Tables[0].Rows[i]["officeid"].ToString() + "',");
}
if (sbList.ToString() != "")
{
string strList = sbList.ToString().TrimEnd(',');
strSql = "delete from tbl_member where officeid in (" + sbList + ") or officeid is null";
int affectRows = SqlHelper.ExecuteSql(strConn, strSql);
}
string sql = "insert into tbl_member select * from [Excel 8.0;database=" + filename + "].[用户表$]
SqlHelper.ExecuteSql(strConn, sql);
strOper = "Import";
}
}
catch (Exception eIm)
{
MessageBox.Show("导入时出错:" + eIm.Message);
}
/// <summary>
/// 主线程显示稍候框
/// </summary>
private void ProgressShow()
{
frmProgress = new FrmProgress();
frmProgress.StartPosition = FormStartPosition.CenterScreen;
frmProgress.ShowDialog();
}
private void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
frmProgress.Close();
frmProgress.Dispose();
if (e.Error == null)
{
if (strOper == "Export")
MessageBox.Show("导出数据成功", "导出数据", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (strOper == "Import")
MessageBox.Show("导入数据成功", "导入数据", MessageBoxButtons.OK, MessageBoxIcon.Information);
strOper = "";
}
}
}