我的项目中包含了TemplateExcel,我想将我的数据表导出到Excel,我想复制并保存这个模板,数据到处都想保存,我该怎么办?
答案 0 :(得分:6)
你可以通过Excel Interop这样做:
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。这需要清理,添加错误处理,重构等,但基础就在那里。
Graham方法归功于GetExcelColumnName。
答案 1 :(得分:0)
1您可以使用本文 - 基于RenderControl
,但您使用的是绑定的网格
链接: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