C# Excel 读取导入数据库


使用Aspose.Cells组件。

表格第一行为表头合并,第二行为数据名称,从第三行开始数据。

   if (xtraOpenFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (propertyDatas != null)
                {
                    propertyDatas.Clear();
                }
                Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(xtraOpenFileDialog1.FileName);
                var worksheets = workbook.Worksheets;
                propertyDatas = new List<PropertyData>();
                foreach (var sheet in worksheets)
                {
                    List<string> list = new List<string>();
                    List<string> group = new List<string>();

                    Dictionary<string, string> DGroup_Name = new Dictionary<string, string>();

                    for (int i = 0; i <= sheet.Cells.MaxDataColumn; i++)
                    {
                        list.Add(sheet.Cells[1, i].StringValue);

                        if(sheet.Cells[0, i].IsMerged)
                        {
                            var range=    sheet.Cells[0, i].GetMergedRange();
                            group.Add(sheet.Cells[range.FirstRow, range.FirstColumn].StringValue);
                        }
                        else
                        {
                            group.Add(sheet.Cells[0, i].StringValue);
                        }
                    
                    }
                
                    // Excel 的第一行 为标题行,第一列为模型编号列
                    for (int j = 2; j <= sheet.Cells.MaxDataRow; j++)
                    {
                        for (int i = 0; i <= sheet.Cells.MaxDataColumn; i++)
                        {
                            PropertyData property = new PropertyData();
                            property.ModelCode = sheet.Cells[j, 0].StringValue;
                            property.Name = list[i];
                            if (sheet.Cells[j, i].Type == CellValueType.IsNull)
                            {
                                property.Value = "";
                            }
                            else
                            {
                                property.Value = sheet.Cells[j, i].StringValue;
                            }

                            property.GroupName = group[i];
                            //添加到集合中
                            propertyDatas.Add(property);
                        }
                       
                    }
                }
                gridControl1.DataSource = null;
                gridControl1.DataSource = propertyDatas;
                simpleButton2.Enabled = true;
            }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM