我的项目中包含了 TemplateExcel,我想将我的数据表导出到 Excel,我想复制并保存这个模板以及我想保存的任何地方的数据,我该怎么做?
问问题
34422 次
2 回答
7
您可以通过 Excel 互操作来做到这一点,如下所示:
using System;
using System.Data;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication3
{
class Program
{
static void Main()
{
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
DataTable dataTable = new DataTable();
DataColumn column = new DataColumn("My Datacolumn");
dataTable.Columns.Add(column);
dataTable.Rows.Add(new object[] {"Foobar"});
var columns = dataTable.Columns.Count;
var rows = dataTable.Rows.Count;
Excel.Range range = worksheet.Range["A1", String.Format("{0}{1}", GetExcelColumnName(columns), rows)];
object[,] data = new object[rows,columns];
for (int rowNumber = 0; rowNumber < rows; rowNumber++)
{
for (int columnNumber = 0; columnNumber < columns; columnNumber++)
{
data[rowNumber, columnNumber] = dataTable.Rows[rowNumber][columnNumber].ToString();
}
}
range.Value = data;
workbook.SaveAs(@"C:\test\whatever123.xlsx");
workbook.Close();
Marshal.ReleaseComObject(application);
}
private static string GetExcelColumnName(int columnNumber)
{
int dividend = columnNumber;
string columnName = String.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName;
}
}
}
我在这里所做的只是创建一个System.Data.DataTable
对象,用一些数据填充它,然后将其导出到 Excel。这需要清理,添加错误处理,重构等,但基础在那里。
于 2012-09-21T15:54:53.780 回答
0
1 您可以使用这篇文章-基于RenderControl
,但您在绑定的 Grid 上工作
链接: http: //www.codeproject.com/Tips/344604/Export-to-EXCEL-from-Datatable-in-Csharp-Net
2 您可以基于表格进行开发
链接: http: //www.codeproject.com/Tips/406704/Export-DataTable-to-Excel-with-Formatting-in-Cshar
于 2012-09-21T15:37:35.533 回答