如何将数据追加到 Excel 文件中
本文关键字:Excel 文件 追加 数据 | 更新日期: 2023-09-27 18:34:23
designation table:
deg_no deg_name
1 XYZ
2 ABC
3 pqs
4 qwe
5 tyu
6 pqr
7 lkj
8 you
9 zzz
10 xxx
ds = cls.ReturnDataSet("RetriveData_Alias1",
new SqlParameter("@Field", "deg_no"),
new SqlParameter("@TblNm", "designation"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataSet ds1 = new DataSet();
ds1 = cls.ReturnDataSet("RetriveData_Alias1",
new SqlParameter("@Field", "user_id,user_name"),
new SqlParameter("@TblNm", "User_details"),
new SqlParameter("@WhereClause", "where deg_no ='" + ds.Tables[0].Rows[i]["deg_no"].ToString() + "' "));
}
这个 for 循环将运行到 deg_no=10 并提供所有用户详细信息,并根据需要提供完美的输出输出。
但我想将这些数据写入Excel文件:user_details.xls
假设当 i=1 时,它会给你
user_id user_name deg_no
1 xyz 1
对于 i=2
user_id user_name deg_no
2 pqr 3
等等...
但没有每次都创建新文件.
假设在第一个循环中,它将插入 user_id =1 的记录然后在第二个循环中,user_id=2 的详细信息将附加到同一文件中,而不创建新文件。
我该怎么做?
从数据库数据生成 Excel 文件,报告解决方案是最灵活的方法。另一方面,如果要将数据添加到现有文件中,则可以使用Open XML SDK或更高级别的库(如EPPlus(操作Excel文件。EPPlus 作为 NuGet 包提供,因此可以轻松地将其添加到项目中。
EPPlus的项目现场包含各种样本。创建 Excel 工作表可以像以下那样简单:
FileInfo newFile = new FileInfo(outputDir.FullName + @"'sample6.xlsx");
ExcelPackage pck = new ExcelPackage(newFile);
//Add the Content sheet
var ws = pck.Workbook.Worksheets.Add("Content");
ws.Cells["B1"].Value = "Name";
ws.Cells["C1"].Value = "Size";
ws.Cells["D1"].Value = "Created";
ws.Cells["E1"].Value = "Last modified";
EPPlus 还允许您使用 LINQ 查询 Excel Sheets,甚至直接将 IEnumerable 集合转换为 Excel Tables:
ws.Cells["A1"].LoadFromCollection(myList, true);
这将用 myList 中对象的属性值填充一个表。
EPPlus也有从DataTables和DataReaders读取的方法。这允许您像已经一样读取数据集,然后将每个数据表添加到工作表的适当位置,例如:
ws.Cells["A1"].LoadFromDataTable(ds1.Tables[0], true);
...
ws.Cells["A30"].LoadFromDataTable(ds1.Tables[0], true);
这样,当您不想使用完整的报告解决方案时,可以使用EPPlus生成快速和脏的Excel报告。
阅读有关 ASP.Net 报表查看器控件的信息
愿这对你有所帮助
ASP.Net 报表查看器控件教程(含示例
(或者您可以使用
从 C#.Net 中的数据表导出到 EXCEL
或者您需要 Office 互操作作为参考,然后让我们进行编码
using Microsoft.Office.Interop.Excel;
public void DataSetsToExcel(List<DataSet> dataSets, string fileName)
{
Microsoft.Office.Interop.Excel.Application xlApp =
new Microsoft.Office.Interop.Excel.Application();
Workbook xlWorkbook = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Sheets xlSheets = null;
Worksheet xlWorksheet = null;
foreach (DataSet dataSet in dataSets)
{
System.Data.DataTable dataTable = dataSet.Tables[0];
int rowNo = dataTable.Rows.Count;
int columnNo = dataTable.Columns.Count;
int colIndex = 0;
//Create Excel Sheets
xlSheets = xlWorkbook.Sheets;
xlWorksheet = (Worksheet)xlSheets.Add(xlSheets[1],
Type.Missing, Type.Missing, Type.Missing);
xlWorksheet.Name = dataSet.DataSetName;
//Generate Field Names
foreach (DataColumn dataColumn in dataTable.Columns)
{
colIndex++;
xlApp.Cells[1, colIndex] = dataColumn.ColumnName;
}
object[,] objData = new object[rowNo, columnNo];
//Convert DataSet to Cell Data
for (int row = 0; row < rowNo; row++)
{
for (int col = 0; col < columnNo; col++)
{
objData[row, col] = dataTable.Rows[row][col];
}
}
//Add the Data
Range range = xlWorksheet.Range[xlApp.Cells[2, 1], xlApp.Cells[rowNo + 1, columnNo]];
range.Value2 = objData;
//Format Data Type of Columns
colIndex = 0;
foreach (DataColumn dataColumn in dataTable.Columns)
{
colIndex++;
string format = "@";
switch (dataColumn.DataType.Name)
{
case "Boolean":
break;
case "Byte":
break;
case "Char":
break;
case "DateTime":
format = "dd/mm/yyyy";
break;
case "Decimal":
format = "$* #,##0.00;[Red]-$* #,##0.00";
break;
case "Double":
break;
case "Int16":
format = "0";
break;
case "Int32":
format = "0";
break;
case "Int64":
format = "0";
break;
case "SByte":
break;
case "Single":
break;
case "TimeSpan":
break;
case "UInt16":
break;
case "UInt32":
break;
case "UInt64":
break;
default: //String
break;
}
//Format the Column accodring to Data Type
xlWorksheet.Range[xlApp.Cells[2, colIndex],
xlApp.Cells[rowNo + 1, colIndex]].NumberFormat = format;
}
}
//Remove the Default Worksheet
((Worksheet)xlApp.ActiveWorkbook.Sheets[xlApp.ActiveWorkbook.Sheets.Count]).Delete();
//Save
xlWorkbook.SaveAs(fileName,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
XlSaveAsAccessMode.xlNoChange,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
xlWorkbook.Close();
xlApp.Quit();
GC.Collect();
}
请注意,您必须命名数据集,这将是Excel中工作表的名称。
DataSet dataSet1 = new DataSet("My Data Set 1");
dataAdapter1.Fill(dataSet1);
DataSet dataSet2 = new DataSet("My Data Set 2");
dataAdapter1.Fill(dataSet2);
DataSet dataSet3 = new DataSet("My Data Set 3");
dataAdapter1.Fill(dataSet3);
List<DataSet> dataSets = new List<DataSet>();
dataSets.Add(dataSet1);
dataSets.Add(dataSet2);
dataSets.Add(dataSet3);
DataSetsToExcel(dataSets, "{Your File Name}")
将 Office 互操作
添加为参考按照以下步骤操作:
On the Project menu, click Add Reference.
On the COM tab, locate Microsoft Excel Object Library, and then click Select. In Visual Studio 2010, locate Microsoft Excel --.- Object Library on the COM tab.
Click OK in the Add References dialog box to accept your selections. If you are prompted to generate wrappers for the libraries that you selected, click “Yes”.