[英]C# read in Excel file
我想将一个excel文件的数据(从A2-A28->第一列)放入我的C#程序中。 我的代码如下所示:
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
private void btnEinlesen1_Click(object sender, EventArgs e)
{
ofd.Filter = "Excel (*.xls;*.xlsx)|*.xls;*.xlsx;|" + "All files (*.*)|*.*";
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
ofd.Title = "Exceldatei öffnen";
ofd.FileName = "";
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
Excel.Application xlApp; //Excel starten
Excel.Workbook xlWorkBook; // Dokument anlegen
Excel.Worksheet xlWorkSheet; // Blatt anlagen
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(ofd.FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //Zugriff auf erstes Sheet
string aux = "";
for (int i = 2; i <= 28; i++)
{
aux += xlWorkSheet.get_Range("A" + i.ToString(), "A" + i.ToString()).Value.toString() + "/";
}
aux.ToArray(); //wandelt string aux in ein array um
MessageBox.Show(aux.ToString());
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
但是每次在excel文件中读取1(其中A2-A28充满数字)时,我都会收到错误消息:
有什么问题?
http://aspxdeveloper.blogspot.com.au/2013/03/read-excel-file-in-c.html
protected void BtnReadExcel_Click(object sender, EventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection("
Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=" + Server.MapPath("TestExcel.xlsx") + ";
Extended Properties='Excel 8.0;HDR=Yes;'"
);
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
DataSet ds = new DataSet();
da.Fill(ds);
}
catch (Exception ex)
{
throw;
}
}
无需使用get_Range
方法进行循环。
去掉
string aux = "";
for (int i = 2; i <= 28; i++)
{
aux += xlWorkSheet.get_Range("A" + i.ToString(), "A" + i.ToString()).Value.toString() + "/";
}
aux.ToArray(); //wandelt string aux in ein array um
并添加以下内容:
Excel.Range xlRange = xlWorkSheet.get_Range("A2:A28", System.Reflection.Missing.Value);
System.Array dataArray = (System.Array)(xlRange.Cells.Value2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.