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; }