导出到excel

来源:互联网 发布:毛概网络课程答案2017 编辑:程序博客网 时间:2024/06/06 13:06
private void OutToExcel(System.Data.DataTable dt) { #region 验证可操作性 //定义表格内数据的行数和列数 int rowscount = dt.Rows.Count; int colscount =dt.Columns.Count; //行数必须大于0 if (rowscount <= 0) { MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //列数必须大于0 if (colscount <= 0) { MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //行数不可以大于65536 if (rowscount > 65536) { MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //列数不可以大于255 if (colscount > 255) { MessageBox.Show("数据记录行数太多,不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } #endregion SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "保存为Excel文件"; saveFileDialog.ShowDialog(); if (saveFileDialog.FileName.IndexOf(":") < 0) return; //被点了"取消" Stream myStream; myStream = saveFileDialog.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string columnTitle = ""; try { //写入列标题 for (int i = 0; i < colscount; i++) { if (i > 0) { columnTitle += "/t"; } columnTitle += dt.Columns[i].ColumnName; } sw.WriteLine(columnTitle); //写入列内容 for (int j = 0; j < rowscount; j++) { string columnValue = ""; for (int k = 0; k < colscount; k++) { if (k > 0) { columnValue += "/t"; } if (dt.Rows[j][k]== null) columnValue += ""; else { if (dt.Rows[j][k].GetType() == typeof(string) && dt.Rows[j][k].ToString().StartsWith("0")) { columnValue += "'" + dt.Rows[j][k].ToString(); } else columnValue += dt.Rows[j][k].ToString(); } } sw.WriteLine(columnValue); } sw.Close(); myStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { sw.Close(); myStream.Close(); MessageBox.Show("数据导出成功,共导出"+dt.Rows.Count.ToString()+"条记录"); } }
原创粉丝点击