我正在编写一个从excel表中读取的C#应用程序。它读取整个工作表,但我感兴趣的是只连续读取特定单元格并移动到下一行并再次读取该行中的特定单元格。对于excel中的所有行,未读取或省略的单元格是相同的。以下是我阅读excel的示例代码:
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:/test.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for(int i=1; i <= rowCount; i++)
{
for(int j=1; j<=colCount; j++)
{
MessageBox.Show(xlRange.Cells[i,j].Value2.ToString());
}
}
}
答案 0 :(得分:0)
您可以使用OleDB而不是Excel.Interop。您的问题只需要读取单元格值,因此更容易将excel文件视为数据表本身....
string fileName = @"C:\test.xlsx";
string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=0'", fileName);
using(OleDbConnection cn = new OleDbConnection(connectionString))
{
cn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Column1, Column2, Column3 From [Sheet1$]", cn);
OleDbDataReader rd = cmd.ExecuteReader();
while(rd.Read())
{
Console.WriteLine("Loop");
Console.WriteLine(rd.GetString(0));
Console.WriteLine(rd.GetString(1));
Console.WriteLine(rd.GetString(2));
Console.WriteLine();
}
}
几点说明:
我正在使用ACE.OleDB,因为您的文件具有XLSX扩展名 我假设你的文件在名为Column1的第一行中有列标题。等....