日期:2014-05-19  浏览次数:20747 次

50分求教如何向Excel中插入数据
问题是这样,从SQL中筛选出数据后插入到Excel模板指定的行列中,请问题如何操作?中否需要引用Excel引擎?Excel中的行、列如何写?希望有完整代码,谢谢大侠们!!!

------解决方案--------------------
1.引用COM组件access10

Access.ApplicationClass oAccess = new Access.ApplicationClass();
oAccess.Visible = false;
//ACCESS10:
oAccess.OpenCurrentDatabase( "d:\\test.mdb ",false, " ");
//导入access
oAccess.DoCmd.TransferSpreadsheet(Access.AcDataTransferType.acExport,Access.AcSpreadSheetType.acSpreadsheetTypeExcel9, "一个表名 ", "d:\\test.xls ",true,null,null);
//导入txt
//oAccess.DoCmd.TransferText(Access.AcTextTransferType.acExportDelim, " ", "一个表名 ", "d:\\test.txt ",true, " ",0);
oAccess.CloseCurrentDatabase();
oAccess.DoCmd.Quit(Access.AcQuitOption.acQuitSaveNone);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oAccess);
oAccess = null;
MessageBox.Show( "导入成功 ");
------解决方案--------------------
不是access是excel
通过excel.application如下:
int RowNum = 1;
object missing=Missing.Value;
Excel.Application myExcel=new Excel.ApplicationClass( );
Excel.Workbook myBook = myExcel.Application.Workbooks.Add(missing);
myExcel.Visible=false;
Excel.Worksheet MySheet=(Excel.Worksheet)myBook.Worksheets[1];

for(int i=0;i <TableDG.Rows.Count;i++)
{
MySheet.Cells[RowNum,1] = i+1;
for(int j=0;j <TableDG.Columns.Count;j++)
{
MySheet.Cells[RowNum,j+2] = TableDG.Rows[i][j].ToString();
}
RowNum ++;
}


对各行各列的格式进行定义的话,你可以通过录制宏来看具体的代码如何写

简单的例子
//将列头居中
MySheet.get_Range(MySheet.Cells[RowNum,1],MySheet.Cell[RowNum,TableDG.Columns.Count + 1]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

------解决方案--------------------
using Excel=Microsoft.Office.Interop.Excel;
using ExcelC=Microsoft.Office.Core;

Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Workbooks.Open(@ "D:\CExcel\bin\Debug\Simple.xls ",
0, false, 5, " ", " ", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, " ",
true, false, 0, true, false, false);
//Excel.Workbook wbook = app.Workbooks[0];
Excel.Worksheet wsheet = (Excel.Worksheet)app.Workbooks.get_Item(1).Sheets.get_Item(1);
Excel.Range ran = (Excel.Range)wsheet.Cells[1, 1];
MessageBox.Show(app.Workbooks[1].FullName + ": " + ran.Text);

app.Workbooks.Close();
app.Quit();