我手中有一个与excel相同的数据库表,并且我想读取此excel中的值并将其保存在数据库中,同时excel还希望通过提供对是否值是否为空。我想用mvvm来执行此操作。如果您单击保存按钮以检查数据库是否正确并且要保存。 如果您擅长于空白列等,如果您希望将其打印到datagrid。 如果没有,我想打印到数据库
Excel是:
ID NAME CLASS
12 JOHN 3
24 Alex 7
数据库表为:
ID NAME CLASS
我想读取此excel,将excel插入到table。但是我不读取并插入到table。 // [A1:C2]这是获取excel中的列数和带代码的行数的方法。因为此位置可能会减少和增加。
I try to:
//Excel Read Code
Excel.Application app=new Excel.Application();
Excel.Workbook workbook=app.workbooks.Open(fileName,Type.Missing,Type.Missing);
Excel.Worksheet sheet=workbook.Sheets[1];
Excel.Range range=sheet.UsedRange;
DataTable dt=new DataTable();
int col =range.Columns.Count;
int row= range.Rows.Coun;
for(int rowNumber=1 ;rowNumber <=sheet.Rows.Count; rowNumber++)
{
Excel.Range range=(Excel.Range)sheet.get_Range("A1:C2",Type.Missing);
System.Array myvalues=(System.Array)range.Cells.Value2;
if(myvalues.GetValue(1,1) ==null)
{
break;
Dictionary<string,string> dic=new Dictionary<string,string>();
foreach(Excel.Range cell in range)
{
string cellIndex=cell.get_AddressLocal(fale,false,Excel.xlReferenceStyle.alA1,Type.Missing,Type.Missin);
string cellValue=Convert.ToString(cell.Value2);
string cellValueColumn3=Convert.ToString(cell.Value2);
dic.Add(cellIndex,cellValue);
}
// Insert Table Code
OleDbCommand=new OleDbCommand();
using(DbDataReader dr=command.ExecuteReader())
{
//SQL connection
string sqlcon= " " ; //write datasource vs.
using(SqlBulkCopy bulkCopy=new SqlBulkCopy(sqlcon))
{
bulkCopy.DestinationTable = "STUDENTS";
bulkCopy.WriteToServer(dr);
MessageBox.Show("İnserted");
}
}
答案 0 :(得分:0)
`public void ReadExcel(string path){
try
{
System.Data.DataTable dt = new System.Data.DataTable();
Microsoft.Office.Interop.Excel.Application xlApp = new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
for (int r = 2; r <= rowCount; r++)
INSERT INTO mytable (ID,NAME,CLASS)VALUES (dr[c - 1] = xlRange.Cells[r, c].Text,
xlRange.Cells[r,c+1].Text, xlRange.Cells[r,c+2].Text);
}
}
}catch(Exception ex){throw ex;}
`