winform excel导入mysql_Winform中Excel数据导入与导出

1.说明:导出的效率说不上很高,但至少是可以接收的.参考网上很多高效导出Excel的方法,实现到时能够实现的,导出速度也很快,不过缺陷在与不能很好的进行单元格的化,比如上图中的"拼音码"字段中的值"000000000012120",在导出后就显示"12120",挺郁闷的!o(∩_∩)o,废话不说了,进入正题.......

2.首先添加Excel引用3.实现///

/// DataGridView导出Excel

///

/// Excel文件中的标题

/// DataGridView控件

/// 0:成功;1ataGridView中无记录;2:Excel无法启动;9999:异常错误

private int ExportExcel(string strCaption, DataGridView myDGV)

{

int result = 9999;

//列索引,行索引,总列数,总行数int ColIndex = 0;

int RowIndex = 0;

int ColCount = myDGV.ColumnCount;

int RowCount = myDGV.RowCount;

if (myDGV.RowCount == 0)

{

result = 1;

}

//创建Excel对象Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

if (xlApp == null)

{

result = 2;

}

try

{

//创建Excel工作薄Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);

Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];

//设置标题Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); //标题所占的单元格数与DataGridView中的列数相同range.MergeCells = true;

xlApp.ActiveCell.FormulaR1C1 = strCaption;

xlApp.ActiveCell.Font.Size = 20;

xlApp.ActiveCell.Font.Bold = true;

xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;

//创建缓存数据object[,] objData = new object[RowCount + 1, ColCount];

//获取列标题foreach (DataGridViewColumn col in myDGV.Columns)

{

objData[RowIndex, ColIndex++] = col.HeaderText;

}

//获取数据for (RowIndex = 1; RowIndex < RowCount; RowIndex++)

{

for (ColIndex = 0; ColIndex < ColCount; ColIndex++)

{

if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string)

|| myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))//这里就是验证DataGridView单元格中的类型,如果是string或是DataTime类型,则在放入缓存时在该内容前加入" ";

{

objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value;

}

else

{

objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value;

}

}

System..Forms.Application.DoEvents();

}

//写入Excel

range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, ColCount]);

range.Value2 = objData;

//保存xlBook.Saved = true;

xlBook.SaveCopyAs("C:\\测试" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");

//返回值result = 0;

}

catch (Exception err)

{

result = 9999;

}

finally

{

xlApp.Quit();

GC.Collect(); //强制回收}

return result;

}

4.调用方法(上图中"生成Excel文件"按钮的on

Click事件)

private void button4_Click(object sender, EventArgs e)

{

int result = this.ExportExcel("测试", this.dataGridView1); //this.dataGridView1ataGridView控件MessageBox.Show(result.ToString());

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值