Microsoft.Office.Interop.Excel.ApplicationClass app = new microsoft.Office.Interop.Excel.ApplicationClass();
Workbook wbook = app.Workbooks.Open(path, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Worksheet ws = (Worksheet)wbook.Worksheets[1];
到这步后不知道怎么确定ws的读取界限了?试过rows.count cells.count 等,但显示的是整个Excel的大小,数量惊人。怎么判断有内容部分的范围,望高手赐教。
Workbook wbook = app.Workbooks.Open(path, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Worksheet ws = (Worksheet)wbook.Worksheets[1];
到这步后不知道怎么确定ws的读取界限了?试过rows.count cells.count 等,但显示的是整个Excel的大小,数量惊人。怎么判断有内容部分的范围,望高手赐教。
有没有可以一下将Excel表格直接转成DataTable的方法?
OleDbConnection con = new OleDbConnection(strConn);
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
public void ExcelIntoDatagridView()
{ //打开一个文件选择框
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Excel文件";
ofd.FileName = "";
ofd.Filter = "Excel文件(*.xls)|*.xls";
try
{ if (ofd.ShowDialog() == DialogResult.OK)
{
string tableName = "";
if (arratlist != null)
{
arratlist.Clear();
}
string Path = ofd.FileName;
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
tableName = schemaTable.Rows[0][2].ToString().Trim();
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
arratlist.Add(schemaTable.Rows[i][2].ToString().TrimStart('\'').Trim('\'', '$'));//
}
arratlist.Sort();
string strExcel = "Select * From [" + tableName + "]";
OleDbCommand cmd = new OleDbCommand(strExcel, conn);
DataTable excelDt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(strExcel, conn);
da.Fill(excelDt);
conn.Close();
MessageBox.Show("excel 导入成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("导入文件时出错,文件可能正被打开","提示");
} }