如何将多个DataTable数据导入到Excel中
假设,我有两个DataTable dt1和dt2列和行都不固定,我现在想将这两个DataTable导入到Excel的一个Sheet1中,并且dt2的数据显示在dt1的下方,如何实现?由于时间急,任务多,请给个详细点的代码,谢谢
大家节日快乐哈 --------------------编程问答-------------------- 添加excel com引用
然后分别遍历你的两个table往里写就行了. --------------------编程问答--------------------
Excel.ApplicationClass excel = new Excel.ApplicationClass();--------------------编程问答-------------------- 如果两个DataTable的数据结构一样,那么你可以先将2个DataTable 合并
int rowIndex = 1;
int colIndex=0;
excel.Application.Workbooks.Add(true);
System.Data.DataTable table = 你的table,
foreach(DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[1,colIndex] = col.ColumnName;
}
foreach(DataRow row in table.Rows)
{
rowIndex++;
colIndex=0;
foreach(DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
excel.Visible = false;
//excel.Visible = true;
excel.DisplayAlerts = false;
excel.ActiveWorkbook.SaveAs(strExcelFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excel.Quit();
excel=null;
GC.Collect();//垃圾回收
dt2.Merge(dt1);
这样就方便了
--------------------编程问答-------------------- 楼上,没看见表的结构都不固定么?
没啥好办法,,只有遍历table
可以先遍历到数组中,,上面的大虾的效率有点低。。不过也是最基本的。。 --------------------编程问答-------------------- private void button1_Click(object sender, EventArgs e)
{
string pathName = System.Windows.Forms.Application.StartupPath.Trim();
string dateTime = txtdatatime.Text.Split(char.Parse("-"))[0] + "年" + txtdatatime.Text.Split(char.Parse("-"))[1] + "月";
int count = 0;
FileInfo mode = new FileInfo(pathName + "\\model\\Name.xls");
try
{
mode.CopyTo(pathName + "\\temp\\" + dateTime + " 产品名称.xls", true);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
object ming = Type.Missing;
Excel.Application myExcel = new Microsoft.Office.Interop.Excel.Application();
myExcel.Application.Workbooks.Open(pathName + "\\temp\\" + dateTime + " 产品名称.xls", ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming);
myExcel.Visible = false;
Excel.Workbook myBook = myExcel.Workbooks[1];
Excel.Worksheet mySheet = (Excel.Worksheet)myBook.Worksheets[1];
databind();
try
{
if (ds.Tables.Contains("tblClass"))//如果有这个表就把改表的内容清空
{
ds.Tables["tblClass"].Clear();
}
da.Fill(ds, "tblClass");
count = ds.Tables["tblClass"].Rows.Count;//表中的数据的总行数
dataGridView1.DataSource = ds.Tables["tblClass"];
if (count == 0)
{
MessageBox.Show("没有可打印的数据!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
myExcel.Cells[2, 3] = dateTime;//显示时间的位置
for (int i = 0; i < count; i++)
{
((Excel.Range)mySheet.Cells[i + 3, 1]).EntireRow.Insert(0, Excel.XlDirection.xlDown); //添加行
mySheet.Cells[i + 3, 1] = ds.Tables["tblClass"].Rows[i][0].ToString();
mySheet.Cells[i + 3, 2] = ds.Tables["tblClass"].Rows[i][1].ToString();
}
}
Excel.Range r = mySheet.get_Range(mySheet.Cells[3, 1], mySheet.Cells[2 + count, 2]);
r.Select();
myExcel.Run("Macro1",ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming, ming);
myBook.Save();
myExcel.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (myBook != null)
{
myBook.Close(false, ming, ming);
}
myExcel.Workbooks.Close();
myExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
}
finally
{
da.Dispose();
}
}
--------------------编程问答--------------------
这个能将dt2加入到dt1生成的Excel下吗? --------------------编程问答-------------------- excel.Application在哪引用? --------------------编程问答--------------------
给你代码,直接拷贝就可以用了。
//保存到Excel--------------------编程问答-------------------- 引用文件
public void SaveDataTableToExcel(System.Data.DataTable excelTable,string filePath)
{
Microsoft.Office.Interop.Excel.Application app =
new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
//让后台执行设置为不可见
app.Visible = false;
//新增加一个工作簿
Workbook wBook = app.Workbooks.Add(true);
//如果要打开已有的工作簿,则使用下面的注释语句
// Workbook wBook = app.Workbooks.Open(@"C:\YourPath\YourWorkbook.xls",
// missing, missing, missing, missing, missing, missing, missing,
// missing, missing, missing, missing, missing,missing, missing);
//取得一个工作表
//如果打开了已有的工作簿,也可以这样获取工作表Worksheet wSheet = wBook.ActiveSheet as Worksheet
Worksheet wSheet = wBook.Worksheets[1] as Worksheet;
if (excelTable.Rows.Count > 0)
{
int row = 0;
row = excelTable.Rows.Count;
int col = excelTable.Columns.Count;
allsize = row;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
string str = excelTable.Rows[i][j].ToString();
wSheet.Cells[i + 1, j + 1] = str;
}
}
}
int size = excelTable.Columns.Count;
for (int i = 0; i < size; i++)
{
wSheet.Cells[1, 1 + i] = excelTable.Columns[i].ColumnName;
}
//设置禁止弹出保存和覆盖的询问提示框
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
//保存工作簿
wBook.Save();
//保存excel文件
app.Save(filePath + "\\导出excel.xls");
}
catch(Exception err)
{
MessageBox.Show("导入Excel出错!错误原因:"+ err.Message, "错误提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
//确保Excel进程关闭
app.Quit();
app = null;
}
}
using Microsoft.Office.Interop.Excel;--------------------编程问答-------------------- 错了:
using System.Reflection;
using DMSClient.Lib;
using DMSClient.DMSCtrl;
这样:
using Microsoft.Office.Interop.Excel;--------------------编程问答-------------------- 楼主可以结贴给分了:) --------------------编程问答-------------------- 这个能将dt2加入到dt1生成的Excel下吗?
--------------
能.你可以把我给你的代码写成一个方法.传一个DataTable的参数
或是你把两个Table合成一个(数据格式,结构要兼容),然后导. --------------------编程问答-------------------- 为什么我引用“using Microsoft.Office.Interop.Excel”出错? --------------------编程问答--------------------
我引用这个一直出错,而我在组件里也找不到这个,怎么弄? --------------------编程问答--------------------
我在引用你的函数时,能否最后保存时不覆盖原来的而直接存在原来dt1的下面?
补充:.NET技术 , C#