Home Backend Development C#.Net Tutorial c# Implementation code for importing Excel data into the database

c# Implementation code for importing Excel data into the database

Jan 19, 2017 am 10:44 AM

c#将Excel数据导入到数据库的实现代码

假如Excel中的数据如下:

c# Implementation code for importing Excel data into the database

数据库建表如下:

c# Implementation code for importing Excel data into the database

其中Id为自增字段:

c# Implementation code for importing Excel data into the database

代码:

1

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

43

44

45

46

47

48

49

50

51

52

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

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.OleDb;

using System.Configuration;

using System.Data.SqlClient;

 

namespace InExcelOutExcel

{

    public partial class ExcelToDB : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            FileSvr fileSvr = new FileSvr();

            System.Data.DataTable dt = fileSvr.GetExcelDatatable

            ("C:\\Users\\NewSpring\\Desktop\\Demo\\InExcelOutExcel\\InExcelOutExcel\\excel\\ExcelToDB.xlsx", "mapTable");

            fileSvr.InsetData(dt);

        }

    }

    class FileSvr

    {

        /// <summary>

        /// Excel数据导入Datable

        /// </summary>

        /// <param name="fileUrl"></param>

        /// <param name="table"></param>

        /// <returns></returns>

        public System.Data.DataTable GetExcelDatatable(string fileUrl, string table)

        {

            //office2007之前 仅支持.xls

            //const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=&#39;Excel 8.0;IMEX=1&#39;;";

            //支持.xls和.xlsx,即包括office2010等版本的   HDR=Yes代表第一行是标题,不是数据;

            const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties=&#39;Excel 12.0; HDR=Yes; IMEX=1&#39;";

 

            System.Data.DataTable dt = null;

            //建立连接

            OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));

            try

            {

                //打开连接

                if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)

                {

                    conn.Open();

                }

                System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

 

                //获取Excel的第一个Sheet名称

                string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();

 

                //查询sheet中的数据

                string strSql = "select * from [" + sheetName + "]";

                OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);

                DataSet ds = new DataSet();

                da.Fill(ds, table);

                dt = ds.Tables[0];

 

                return dt;

            }

            catch (Exception exc)

            {

                throw exc;

            }

            finally

            {

                conn.Close();

                conn.Dispose();

            }

 

        }

 

        /// <summary>

        /// 从System.Data.DataTable导入数据到数据库

        /// </summary>

        /// <param name="dt"></param>

        /// <returns></returns>

        public int InsetData(System.Data.DataTable dt)

        {

            int i = 0;

            string lng = "";

            string lat = "";

            string offsetLNG = "";

            string offsetLAT = "";

 

            foreach (DataRow dr in dt.Rows)

            {

                lng = dr["LNG"].ToString().Trim();

                lat = dr["LAT"].ToString().Trim();

                offsetLNG = dr["OFFSET_LNG"].ToString().Trim();

                offsetLAT = dr["OFFSET_LAT"].ToString().Trim();

 

                //sw = string.IsNullOrEmpty(sw) ? "null" : sw;

                //kr = string.IsNullOrEmpty(kr) ? "null" : kr;

 

                string strSql = string.Format("Insert into DBToExcel (LNG,LAT,OFFSET_LNG,OFFSET_LAT)

                Values (&#39;{0}&#39;,&#39;{1}&#39;,{2},{3})", lng, lat, offsetLNG, offsetLAT);

 

                string strConnection = ConfigurationManager.ConnectionStrings["ConnectionStr"].ToString();

                SqlConnection sqlConnection = new SqlConnection(strConnection);

                try

                {

                    // SqlConnection sqlConnection = new SqlConnection(strConnection);

                    sqlConnection.Open();

                    SqlCommand sqlCmd = new SqlCommand();

                    sqlCmd.CommandText = strSql;

                    sqlCmd.Connection = sqlConnection;

                    SqlDataReader sqlDataReader = sqlCmd.ExecuteReader();

                    i++;

                    sqlDataReader.Close();

                }

                catch (Exception ex)

                {

                    throw ex;

                }

                finally

                {

                    sqlConnection.Close();

 

                }

                //if (opdb.ExcSQL(strSql))

                //    i++;

            }

            return i;

        }

    }

}

Copy after login

运行结果:

c# Implementation code for importing Excel data into the database


以上就是c#将Excel数据导入到数据库的实现代码的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Access Modifiers in C# Access Modifiers in C# Sep 03, 2024 pm 03:24 PM

Guide to the Access Modifiers in C#. We have discussed the Introduction Types of Access Modifiers in C# along with examples and outputs.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

C# StringReader C# StringReader Sep 03, 2024 pm 03:23 PM

Guide to C# StringReader. Here we discuss a brief overview on C# StringReader and its working along with different Examples and Code.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

BinaryWriter in C# BinaryWriter in C# Sep 03, 2024 pm 03:22 PM

Guide to BinaryWriter in C#. Here we discuss syntax and explanation, how it works with examples to implement with proper codes.

See all articles