C#winform导出Excel表

//用导出之前引用EXcel.dll(microsoft.office.excel.dll)

private void 领导人词库ToolStripMenuItem2_Click(object sender, EventArgs e)
{
//创建一个Excel文件
Excel.Application myExcel = new Excel.Application();
myExcel.Application.Workbooks.Add(true);

//写标题
myExcel.Cells[1, 1] = "职务";
myExcel.Cells[1, 2] = "职务级别";
myExcel.Cells[1, 3] = "领导人";

int ii = 1; //导出到Excel的自增变量


myExcel.Cells.NumberFormatLocal = "@"; //左对齐


myExcel.get_Range("A1", "A1").ColumnWidth = 25;//列宽
myExcel.get_Range("B1", "B1").ColumnWidth = 14;
//myExcel.Cells.Font.Bold = true; //字体加粗
try
{
//1.添加国家领导级别的职务(由于职务级别排序为:国家领导11.12.13.14...
//而以后的省领导,市领导职务排序为:2.3.4...)
//为了能使其按顺序排下来,分成了两次的添加。


DataTable dtHeadship = myBll.dtheadship_t1(DBConnectS);

//2.添加非国家领导的职务(省领导职务,市领导,区领导。。。)
DataTable dtHeadship2 = myBll.dtheadship_t2(DBConnectS);

if ((dtHeadship.Rows.Count + dtHeadship2.Rows.Count) > 0)
{
Sprogress = new Setting.progressForm();
Sprogress.Show(); //如果有数据导出就弹出进度条


}
if (dtHeadship.Rows.Count > 0)
{
for (int i = 0; i < dtHeadship.Rows.Count; i++)
{
ii++;
string h4 = null; //职务对应的领导人变量
string h1 = dtHeadship.Rows[i][1].ToString().Trim(); //职务
string h2 = dtHeadship.Rows[i][2].ToString().Trim(); //级别
// string h3 = dtHeadship.Rows[i][3].ToString().Trim(); //排序

//将级别号转化成对应的级别名称
h2 = myBll.m_layerChange(DBConnectS, h2);

//根据职务查找对应的领导人
DataTable dt_h4 = myBll.dtGetHeadship(DBConnectS, h1);
for (int i1 = 0; i1 < dt_h4.Rows.Count; i1++)
{
h4 += "*" + dt_h4.Rows[i1][0].ToString().Trim();
}

//写入Excel
myExcel.Cells[ii, 1] = h1;
myExcel.Cells[ii, 2] = h2;
myExcel.Cells[ii, 3] = h4;

showProgressBar(i, dtHeadship.Rows.Count + dtHeadship2.Rows.Count); //加

载进度条值


}
}

if (dtHeadship2.Rows.Count > 0)
{
for (int j = 0; j < dtHeadship2.Rows.Count; j++)
{
ii++;
string h4 = null; //职务对应的领导人变量
string h1 = dtHeadship2.Rows[j][1].ToString().Trim(); //职务
string h2 = dtHeadship2.Rows[j][2].ToString().Trim(); //级别
// string h3 = dtHeadship2.Rows[j][3].ToString().Trim(); //排序

//将级别号转化成对应的级别名称
h2 = myBll.m_layerChange(DBConnectS, h2);

//根据职务查找对应的领导人
DataTable dt_h4 = myBll.dtGetHeadship(DBConnectS, h1);
for (int i = 0; i < dt_h4.Rows.Count; i++)
{
h4 += "*" + dt_h4.Rows[i][0].ToString().Trim();
}

//写入Excel
myExcel.Cells[ii, 1] = h1;
myExcel.Cells[ii, 2] = h2;
myExcel.Cells[ii, 3] = h4;

showProgressBar(j, dtHeadship.Rows.Count + dtHeadship2.Rows.Count); //加载进度条值


}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
finally
{
//让Excel文件可见
myExcel.Visible = true;
Sprogress.Dispose();
Sprogress.Close();
}
}

相关文档
最新文档