我在这里导出3个表到Excel,我只想转置第一个表。我尝试使用Transpose函数,但似乎我以错误的方式使用它,因为它抛出System.ArgumentException。不确定,转换表的另一种方法是什么。
我也尝试过使用DataView,但即使这样也行不通。以下是我对DataView所做的事情:
static void Main(string[] args)
{
string strSql = ConfigurationManager.AppSettings["Sql"];
DataAccess dsObj = new DataAccess();
DataSet ds= dsObj.GetData(strSql);
DataView transposedDataView = Transpose(ds.Tables[0].Copy()).DefaultView;
var td = transposedDataView.ToTable();
TableData(td, ds.Tables[1], ds.Tables[2]);
}
以下是整个代码
class CreateWorkbook
{
static void Main(string[] args)
{
string strSql = ConfigurationManager.AppSettings["Sql"];
DataAccess dsObj = new DataAccess();
DataSet ds= dsObj.GetData(strSql);
TableData(Transpose(ds.Tables[0]), ds.Tables[1], ds.Tables[2]);
}
private static DataTable Transpose(DataTable dt)
{
DataTable dtNew = new DataTable();
//adding columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
dtNew.Columns.Add(i.ToString());
}
//Changing Column Captions:
dtNew.Columns[0].ColumnName = " ";
//Adding Row Data
for (int k = 1; k < dt.Columns.Count; k++)
{
DataRow r = dtNew.NewRow();
r[0] = dt.Columns[k].ToString();
for (int j = 1; j <= dt.Rows.Count; j++)
r[j] = dt.Rows[j - 1][k];
dtNew.Rows.Add(r);
}
return dtNew;
}
private static void TableData(DataTable Summary, DataTable NewIssue, DataTable Backlog) // Datatable contains data which we want to show in excel report
{
// create a new excel package for writing
using (ExcelPackage workingPkg = new ExcelPackage())
{
//create workbook
ExcelWorkbook wbReport = workingPkg.Workbook;
//Add worksheets in workbook
ExcelWorksheet ws = workingPkg.Workbook.Worksheets.Add("Summary.xlsx");
ExcelWorksheet ws1 = workingPkg.Workbook.Worksheets.Add("NewIssuance.xlsx");
ExcelWorksheet ws2 = workingPkg.Workbook.Worksheets.Add("BuyBack.xlsx");
ws.Cells["A1"].LoadFromDataTable(Summary, true, TableStyles.Medium1);
ws.Cells[ws.Dimension.Address].AutoFitColumns();
ws.Cells["A:H"].Style.Numberformat.Format = "#,##0";
ws1.Cells["A1"].LoadFromDataTable(NewIssuance, true, TableStyles.Medium1);
ws1.Cells[ws1.Dimension.Address].AutoFitColumns();
ws1.Cells["A:H"].Style.Numberformat.Format = "#,##0";
ws2.Cells["A1"].LoadFromDataTable(BuyBack, true, TableStyles.Medium1);
ws2.Cells[ws2.Dimension.Address].AutoFitColumns();
ws2.Cells["A:H"].Style.Numberformat.Format = "#,##0";
workingPkg.SaveAs(new FileInfo(ConfigurationManager.AppSettings["Location"] + DateTime.Now.ToString("_MM_yyyy")+".xlsx"));
}
}
}
答案 0 :(得分:0)
尝试将数据转置到excel中,而不是转置数据表并获取ExcelPackage来读取转置表;数据表从未打算以这种方式使用。 DataTables绝对是完全打算成为一致输入列的数据集合。你不能拿一个包含int列和一个字符串列的2行表,并把它变成一对无类型列,表示一个int行和一个字符串行.. DataTable不能像那样工作
我从未使用过ExcelPackage,所以我不保证下面的代码是100%无错误的(例如我不确定ExcelPackage是使用0基于还是基于1的索引等) ;这个想法是为了表明你可以逐行逐行迭代一个数据表,但你可以逐行地将数据写入excel表列,有效地转置它
for(int tr=0;tr<table.Length;tr++)
for(int tc=0;tc<table.Length;tc++)
worksheet.Cells(tc,tr).Value = table.Rows[tr][tc];