ASP.NET上传Excel并读取Excel中的内容
1
private void Button_Click(object sender, System.EventArgs e)
2
{
3
//获取完整路径
4
string thefullname=this.uploadFile.PostedFile.FileName;
5
6
if(thefullname == "")
7
{
8
Page.RegisterStartupScript("","<script language='javascript'>alert('请选择要上传得Excel文件');</script>");
9
return;
10
}
11
12
int fileLength = this.uploadFile.PostedFile.ContentLength;
13
if(fileLength > 512000)
14
{
15
Page.RegisterStartupScript("","<script language='javascript'>alert('文件已超过500K,无法上传!');</script>");
16
return;
17
}
18
FileInfo info = new FileInfo(thefullname);
19
20
string fileExt = info.Extension;
21
if(fileExt.ToLower() != ".xls")
22
{
23
Page.RegisterStartupScript("","<script language='javascript'>alert('不是Excel文件,请使用正确的文件格式!');</script>");
24
return;
25
}
26
27
string uploadPath = Page.MapPath(@"uploadfile\report.xls");
28
29
bool upSuccess = Upload(uploadPath);
30
if(!upSuccess)
31
{
32
Page.RegisterStartupScript("","<script language='javascript'>alert('文件上传失败!');</script>");
33
return;
34
}
35
36
DataTable table = GetExcelTable(uploadPath);
37
if(table == null)
38
{
39
Page.RegisterStartupScript("","<script language='javascript'>alert('文件读取失败!');</script>");
40
return;
41
}
42
53
54
}
55
56
private bool Upload(string uploadPath)
57
{
58
try
59
{
60
this.uploadFile.PostedFile.SaveAs(uploadPath); //上传Excel并保存,在这里判断是否保存成功
61
return true;
62
}
63
catch
64
{
65
return false;
66
}
67
}
68
69
70
private DataTable GetExcelTable(string uploadPath)
71
{
72
DataSet ds;
73
string Xls_ConnStr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + uploadPath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";//HDR为yes 则第一数据行为列名,为no 则自动为列加列名F1 F2 F3
74
OleDbConnection Conn = new OleDbConnection(Xls_ConnStr);
75
try
76
{
77
Conn.Open();
78
string sql_str = "select * from [Sheet1$]";
79
OleDbDataAdapter da = new OleDbDataAdapter(sql_str,Conn);
80
ds = new DataSet();
81
da.Fill(ds,"excel_data");
82
Conn.Close();
83
}
84
catch
85
{
86
if(Conn.State == ConnectionState.Open)
87
{
88
Conn.Close();
89
}
90
return null;
91
}
92
finally
93
{
94
Conn.Dispose();
95
}
96
97
if(ds == null)
98
{
99
return null;
100
}
101
102
if(ds.Tables.Count < 1)
103
{
104
return null;
105
}
106
107
return ds.Tables[0];
108
}

2

3

4

5

6

7

8

9

10

11
12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42
53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利
This posting is provided "AS IS" with no warranties, and confers no rights.
This posting is provided "AS IS" with no warranties, and confers no rights.