C# excel数据批量导进后添加进数据库中

    在公司,总有user会提出说我不想把excel中的数据一笔笔维护到后台,今天呢,我就来做个小程式,批量导进excel中的数据,再插进数据库中~

    需先选择导进资料到数据库的excel,然后再有个点击确定的按钮,把數據展示到DataGrid,再點擊上傳按鈕添加到數據庫,比较简单


首先,要去下載NPOI,這裡有個地址可以下載~~

http://download.csdn.net/detail/why_n/9858663

建立专案,将下载的文件导进参考~

C# excel数据批量导进后添加进数据库中_第1张图片


xaml部分,界面如第一张图


    
        
            
            
        
        
          
            
                
                    
                        
                        
                    
                    
                        
                        
                        
                    

                    
                        
                            
                        
                                                 
                            
                            
                        
                    
                    
                        
                            
                                
                                
                                
                            
                            

代码部分

這裡主要功能就是讀取excel文件,所以插進數據庫的功能就自己實現啦~

namespace WpfApplication3
{
    /// 
    /// MainWindow.xaml 的互動邏輯
    /// 
    public partial class MainWindow : Window
    {


        System.Data.DataTable ls_excleTable;

        public MainWindow()
        {
            InitializeComponent();
        }


        #region 選擇上傳文件
        private void btnSelectPath_click(object sender, RoutedEventArgs e)
        {

            try
            {
                OpenFileDialog lo_Dialog = new OpenFileDialog();
                lo_Dialog.Filter = "Excel(*.xlsx)|*.xlsx";
                lo_Dialog.RestoreDirectory = true;
                if (lo_Dialog.ShowDialog() == true)
                {
                    txtPath.Text = lo_Dialog.FileName;
                    using (NPOI.ReadExcel.ExportExcelHelper a = new NPOI.ReadExcel.ExportExcelHelper(lo_Dialog.FileName))
                    {

                        ls_excleTable = a.ExcelToDataTable("工作表1", true);

                        if (ls_excleTable.Columns.Count != 2)
                        {
                            MessageBox.Show("導入表格,欄位不對!");
                            return;
                        }
                        ls_excleTable.Columns[0].ColumnName = "EmpNo";   //姓名
                        ls_excleTable.Columns[1].ColumnName = "EmpName";    //工號 

                        if (ls_excleTable != null) dgDetail2.ItemsSource = ls_excleTable.DefaultView;
                        btnLoad.IsEnabled = true;
                    }


                }
            }
            catch (Exception lo_Ex)
            {
                btnLoad.IsEnabled = false;
                MessageBox.Show("錯誤(btnSelectPath_Click):" + lo_Ex.Message, "", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion



        #region 確認上傳
        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            string ls_Msg = "";
            bool lv_DTabHead = true;
            for (int i = 0; i < ls_excleTable.Rows.Count; i++)
            {
               /*
                  该处是插进数据库的动作
                */
            }
           
            MessageBox.Show("儲存成功!");
            btnLoad.IsEnabled = false;
        }
        #endregion
    }
}

namespace NPOI.ReadExcel
{
    public class ExportExcelHelper : IDisposable
    {
        private string fileName = null; //文件名
        private IWorkbook workbook = null;
        private FileStream fs = null;
        private bool disposed;

        public ExportExcelHelper(string fileName)//文件名
        {
            this.fileName = fileName;
            disposed = false;
        }

        /// 
        /// 将DataTable数据导入到excel中
        /// 
        /// 要导入的数据
        /// DataTable的列名是否要导入
        /// 要导入的excel的sheet的名称
        /// 导入数据行数(包含列名那一行)
        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
        {
            int i = 0;
            int j = 0;
            int count = 0;
            ISheet sheet = null;  // 工作表

            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook();
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook();

            try
            {
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet(sheetName);
                }
                else
                {
                    return -1;
                }

                if (isColumnWritten == true) //写入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());

                    }
                    ++count;
                }
                workbook.Write(fs); //写入到excel
                return count;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return -1;
            }
        }

        /// 
        /// 将excel中的数据导入到DataTable中
        /// 
        /// excel工作薄sheet的名称
        /// 第一行是否是DataTable的列名
        /// 返回的DataTable
        public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
        {

            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null       

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                            {
                                //dataRow[j] = row.GetCell(j).ToString();  //被下面if代替 XX 只有一行數據
                                if (row.GetCell(j).CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(row.GetCell(j)))
                                    dataRow[j] = row.GetCell(j).DateCellValue.ToString("yyyy/MM/dd");   //qijiang
                                else
                                {
                                    dataRow[j] = row.GetCell(j).ToString();
                                }
                            }

                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {

                throw ex;   //qijiang

                return null;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (fs != null)
                        fs.Close();
                }

                fs = null;
                disposed = true;
            }
        }
    }
}


具体代码网址:http://download.csdn.net/detail/why_n/9858743











  

你可能感兴趣的:(C#)