如何使用以下方法将此数据表导出为Excel:“ Microsoft.Office.Interop.Excel ”我有这个代码,它会从Master表中获取所有数据,并希望将其导出为excel for更好的视图,不想使用datagrid。我认为有很多关于这个主题的帖子,但通常只是建议使用像“closedxml”这样的广告
OleDbConnection mycon;
DataTable Table = new DataTable("AllData");
mycon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\jm11321\Documents\DB.mdb;Persist Security Info=False");
string command = "Select *From Master";
OleDbCommand oleDbCmd = new OleDbCommand(command,mycon);
OleDbDataAdapter adapt = new OleDbDataAdapter(oleDbCmd);
mycon.Open();
adapt.Fill(Table);
mycon.Close();
感谢任何帮助。
答案 0 :(得分:3)
您必须从here导入Microsoft.Office.Interop.Excel.dll库。在项目中添加新的类文件说ExcelUtility。只需在其中写下以下代码即可。
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelDemo
{
public class ExcelUtility
{
public static void CreateExcel(DataSet ds, string excelPath)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
try
{
//Previous code was referring to the wrong class, throwing an exception
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (int j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = ds.Tables[0].Rows[i].ItemArray[j].ToString();
}
}
xlWorkBook.SaveAs(excelPath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
}
catch (Exception ex)
{
throw ex;
}
}
private static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch
{
obj = null;
}
finally
{
GC.Collect();
}
}
}
}
现在在主代码中,只需传递数据集对象和excel路径,如下所示。
ExcelUtility.CreateExcel(ds, "D:\\Demo.xls");
我已经在我的项目中测试并使用过它。
答案 1 :(得分:3)
我知道已经有了答案,尽管这是另一种方法
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");
这种方法真的很神奇,你可以将数据集表或表放入像这样的工作簿中
var wb = new XLWorkbook();
var dataTable = GetTable("Information");
// Add a DataTable as a worksheet
wb.Worksheets.Add(dataTable);
wb.SaveAs("AddingDataTableAsWorksheet.xlsx");
dll是here