当我执行这个程序时,Excel部分会生成字符串数组:cellValue就好了。
当它插入SQL MDF数据库时:MDFExcel每个单元格显示:“System .__ ComObject”。
如何显示字符串值而不是“System .__ ComObject”?
protected void Button1_Click(Object sender, EventArgs e)
{
DataSet ds = new DataSet();
//From Excel
Microsoft.Office.Interop.Excel.Application exlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exlWb = exlApp.Workbooks.Open(@"C:\Users\Optiplex760\Documents\a Excel\ExcelToMDF.xls");
Microsoft.Office.Interop.Excel.Worksheet exlWs= exlWb.Sheets["Sheet1"];
Microsoft.Office.Interop.Excel.Range usedRange = exlWs.UsedRange;
int col = Convert.ToInt32(usedRange.Columns.Count);
int row = Convert.ToInt32(usedRange.Rows.Count);
exlApp.Visible = true;
string[,] cellValue = new string[row + 1, col + 1];
for (int j = 1; j <= row-1; j++)
{
for (int k = 1; k <= col-1; k++)
{
cellValue[j, k] = exlWs.Cells[j+1,k+1].ToString();
}
}
exlWb.Close();
exlWs = null;
exlWb = null;
exlApp.Quit();
exlApp = null;
//To MSSQL
String connStr, cmdStr;
connStr = ConfigurationManager.ConnectionStrings["MDFExceldb"].ConnectionString;
for (int h = 1; h<row; h++)
{
cmdStr = "INSERT INTO [Table1] (col1,col2,col3) VALUES (@col1,@col2,@col3);";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("@col1", cellValue[1, h]);
cmd.Parameters.AddWithValue("@col2", cellValue[2, h]);
cmd.Parameters.AddWithValue("@col3", cellValue[3, h]);
cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = ex.ToString();
}
}
}
答案 0 :(得分:0)
Worksheet.Cells
返回Range而不是单个值 - 而Range(RCW对象)未实现合理的ToString;因此它默认为显示的“System .__ ComObject”值。
使用范围的Text
属性,例如
cellValue[j, k] = Convert.ToString(exlWs.Cells[j+1,k+1].Text);
虽然这应该解决眼前的问题,但它也是效率低下的进程。请参阅this response(使用Value/Value2属性)了解如何将Range值作为二维数组进行访问,并减少过多的范围切片。