大家好,又见面了,我是全栈君。
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel;
4
using System.Data;
5
using System.Drawing;
6
using System.Text;
7
using System.Windows.Forms;
8
using System.IO;
9
10
namespace 教务管理系统
11 {
12
class DGVToExcel
13 {
14
public
void SaveAs(DataTable dt)
//另存新档按钮 导出成Excel
15 {
16
try
17 {
18 SaveFileDialog saveFileDialog =
new SaveFileDialog();
19 saveFileDialog.Filter =
“Execl files (*.xls)|*.xls”;
20 saveFileDialog.FilterIndex = 0;
21 saveFileDialog.RestoreDirectory =
true;
22 saveFileDialog.CreatePrompt =
true;
23 saveFileDialog.Title =
“导出Excel到”;
24
if(saveFileDialog.ShowDialog()==DialogResult.OK)
25 {
26 Stream myStream;
27 myStream = saveFileDialog.OpenFile();
28 StreamWriter sw =
new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
29
string str = “”;
30
try
31 {
32
//写标题
33
34 str +=dt.TableName;
35 sw.WriteLine(str);
36
//写内容
37
for (
int j = 0; j < dt.Rows.Count; j++)
38 {
39
string tempStr = “”;
40
for (
int k = 0; k < dt.Columns.Count; k++)
41 {
42
if (k > 0)
43 {
44 tempStr +=
“\t”;
45 }
46 tempStr += dt.Rows[j][k].ToString();
47 }
48 sw.WriteLine(tempStr);
49 }
50 sw.Close();
51 myStream.Close();
52 }
53
catch
54 {
55
56 }
57
finally
58 {
59 sw.Close();
60 myStream.Close();
61 }
62 }
63 }
64
catch
65 { }
66 }
67
68 }
69 }
70
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/108014.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...