我的数据集中有5列。 姓名,年龄,性别,地址和联系电话 那么我在数据集中有3个数据行
我只需要在excel中导出时输入姓名,地址和联系电话。 我怎样才能做到这一点? 即时通讯使用Excel = Microsoft.Office.Interop.Excel; 我只得到第一行..而不是数据集中的所有行
这是我获取值的代码
Microsoft.Office.Interop.Excel.Application ExcelAp = new Microsoft.Office.Interop.Excel.Application();
ExcelAp.Application.Workbooks.Add(Type.Missing);
ExcelAp.Columns.ColumnWidth = 25;
int i =0;
foreach( DataRow datarow in DsNow.Tables[0].Rows)
{
for(i = 0; DsNow.Tables[0].Rows.Count - 1; i ++)
{
ExcelAp.Cells[i + 6, 1] = datarow["name"].ToString();
ExcelAp.Cells[i + 6, 2] =datarow["address"].ToString();
ExcelAp.Cells[i + 6, 3] =datarow["contactnumber"].ToString();
}
}
请帮助
答案 0 :(得分:0)
如果仅使用一个循环可以使用FOREACH和FOR循环。只需对代码进行少量修改即可查看以下代码:
int i =0;
for(i = 0; DsNow.Tables[0].Rows.Count - 1; i ++)
{
ExcelAp.Cells[i + 6, 1] = DsNow.Tables[0].Rows[i]["name"].ToString();
ExcelAp.Cells[i + 6, 2] = DsNow.Tables[0].Rows[i]["address"].ToString();
ExcelAp.Cells[i + 6, 3] = DsNow.Tables[0].Rows[i]["contactnumber"].ToString();
}
答案 1 :(得分:0)
Public void Excel()
{
Microsoft.Office.Interop.Excel.Application app;
Workbook workbook = null;
Worksheet worksheet = null;
Range range = null;
int i,j,k=1;
app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
workbook = app.Workbooks.Add(1);
worksheet = (Worksheet)workbook.Sheets[1];
worksheet.Name = "Sheet1";
worksheet.Cells.Locked = false;
//Column1
j = 1;
range = worksheet.Rows.get_Range("A" + j.ToString(), "A" + j.ToString());
range.Font.Size = 11;
((Range)worksheet.Cells[j, 1]).EntireColumn.ColumnWidth = 15;
range.Font.Bold = true;
range.MergeCells = true;
range.HorizontalAlignment = Constants.xlCenter;
//Content
worksheet.Cells[j, 1] = "Name";
//Column2
range = worksheet.Rows.get_Range("B" + j.ToString(), "B" + j.ToString());
range.Font.Size = 11;
((Range)worksheet.Cells[j, 2]).EntireColumn.ColumnWidth = 15;
range.Font.Bold = true;
range.MergeCells = true;
range.HorizontalAlignment = Constants.xlCenter;
//Content
worksheet.Cells[j, 2] = "Address";
//Column3
range = worksheet.Rows.get_Range("C" + j.ToString(), "C" + j.ToString());
range.Font.Size = 11;
((Range)worksheet.Cells[j, 3]).EntireColumn.ColumnWidth = 15;
range.Font.Bold = true;
range.MergeCells = true;
range.HorizontalAlignment = Constants.xlCenter;
//Content
worksheet.Cells[j, 3] = "Contact Number";
//Loop
DataTable dt = new DataTable();
for (i = 0; i < dt.Rows.Count; i++)
{
//Column1
range = worksheet.Rows.get_Range("A" + k.ToString(), "A" + k.ToString());
worksheet.Cells[k, 1] = dt.Rows[i]["NAME"].ToString();
//Column2
range = worksheet.Rows.get_Range("B" + k.ToString(), "B" + k.ToString());
worksheet.Cells[k, 2] = dt.Rows[i]["ADDRESS"].ToString();
//Column3
range = worksheet.Rows.get_Range("C" + k.ToString(), "C" + k.ToString());
worksheet.Cells[k, 3] = dt.Rows[i]["CONTACT_NUMBER"].ToString();
k = k +1;
}
}