.net 讀取 Excel 文字

Still in VS 2005 IDE

?

Add reference: in COM tab, find "Microsoft Excel blahblah"

Example Code:

OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;

if (openFile.ShowDialog() == DialogResult.Cancel)
{
??? return;
}

string fileName = openFile.FileName;

Excel.Application x = new Excel.ApplicationClass();
Excel.Workbook d;

object nothing = System.Reflection.Missing.Value;

d = x.Workbooks.Open(fileName, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing);
string str = "";

foreach (Excel.Worksheet ws in d.Worksheets)
{
??? foreach (Excel.Range r in ws.UsedRange)
??? {
??????? try
??????? {
??????????? str = str + " " + r.Text;
??????? }
??????? catch (Exception ex)
??????? {
??????????? //MessageBox.Show(ex.Message);
??????? }
??? }
}

MessageBox.Show(str);

if (d != null)
{
??? d.Close(nothing, nothing, nothing);
??? d = null;
}

if (x != null)
{
??? x.Quit();
??? x = null;
}

BTW, if want to treat excel data as a data table, should use OLEDB. Example Code:

string str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ofd.FileName+";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
con = new OleDbConnection(str);
con.Open();
string sql = "select * from [sheet1$]";
dar = new OleDbDataAdapter(sql,str);
ds = new DataSet();
dar.Fill(ds);
for(int i=0;i {
??? for(int j=0;j ??? {
??????? txtbox.Text += ds.Tables[0].Rows[i][j].ToString()+" ";
??? }
??? txtbox.Text += System.Environment.NewLine;
}