多个dataview导出数据
一个dataview使用一下导出
Dim strFilePath As String
ExcelApp = New Microsoft.Office.Interop.Excel.Application
ExcelApp.Visible = True
strFilePath = Application.StartupPath + "\Template\生产报表.xls"
ExcelBook = ExcelApp.Workbooks.Open(strFilePath)
Dim i, j As Integer
For i = 0 To Me.DataGridView1.RowCount - 2
For j = 0 To 7 'Me.DataGridView1.ColumnCount - 1
Try
If Me.DataGridView1(j, i).Value Is System.DBNull.Value Then
ExcelApp.Cells(i + 20, j + 1) = ""
Else
ExcelApp.Cells(i + 20, j + 1) = Me.DataGridView1(j, i).Value.ToString
End If
Catch
End Try
Next j
Next i
如何将多个dataview的数据全部导出到一个excel中一个
[解决办法]
在这个帖子中,我写了一个例子,你可以将excel工作表中不同区域的信息采集到二维数组中,或者写入到excel中。
http://bbs.csdn.net/topics/390691267
[解决办法]
//我贴的是C#,VB得转换
//将DataGridView转为datatable
public static System.Data.DataTable dvtodt(DataGridView dv)
{
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataColumn dc;
for (int i = 0; i < dv.Columns.Count; i++)
{
dc = new System.Data.DataColumn();
dc.ColumnName = dv.Columns[i].HeaderText.ToString();
dt.Columns.Add(dc);
}
for (int j = 0; j < dv.Rows.Count; j++)
{
System.Data.DataRow dr = dt.NewRow();
for (int x = 0; x < dv.Columns.Count; x++)
{
dr[x] = dv.Rows[j].Cells[x].Value;
}
dt.Rows.Add(dr);
}
return dt;
}
private void button1_Click(object sender, EventArgs e)
{
//将datatable合并
System.Data.DataTable dt1 = dvtodt(dataGridView1);
System.Data.DataTable dt2 = dvtodt(dataGridView2);
dt1.Merge(dt2, true, MissingSchemaAction.AddWithKey);
DataTabletoExcel(dt1, "C:\\test.XLS");
}
//将datatable存为excel
public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
{
if (tmpDataTable == null)
return;
int rowNum = tmpDataTable.Rows.Count;
int columnNum = tmpDataTable.Columns.Count;
int rowIndex = 1;
int columnIndex = 0;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Workbook xlBook = xlApp.Workbooks.Add(true);
//将DataTable的列名导入Excel表第一行
foreach (DataColumn dc in tmpDataTable.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
}
//将DataTable中的数据导入Excel中
for (int i = 0; i < rowNum; i++)
{
rowIndex++;
columnIndex = 0;
for (int j = 0; j < columnNum; j++)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();
}
}
//xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));
xlBook.SaveCopyAs(strFileName);
}