[英]How do I export data to a CSV file in C# making sure that Excel can work with it?
[英]How can I export data to an Excel file
我有一个包含数据的 Excel 文件。 我想将它的一些特定行写入我通过代码创建的另一个 Excel 文件。 顺便说一下,我在列表中列出了这些行的索引。 我怎样才能做到这一点?
MS 提供 OpenXML SDK V 2.5 - 请参阅https://msdn.microsoft.com/en-us/library/bb448854(v=office.15).aspx
这可以读写 MS Office 文件(包括 Excel)...
另一种选择见http://www.codeproject.com/KB/office/OpenXML.aspx
如果您需要更多像渲染、公式等,那么有不同的商业库,如 Aspose 和 Flexcel...
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
上面的代码是直接从csharp.net 上取下来的,请在网站上查看。
我使用互操作打开 Excel 并在数据完成后修改列宽。 如果您使用互操作将数据吐到新的 Excel 工作簿中(如果这是您想要的),它会非常慢。 相反,我生成了一个.CSV
,然后在 Excel 中打开了.CSV
。 这有其自身的问题,但我发现这是最快的方法。
首先,转换.CSV
:
// Convert array data into CSV format.
// Modified from http://csharphelper.com/blog/2018/04/write-a-csv-file-from-an-array-in-c/.
private string GetCSV(List<string> Headers, List<List<double>> Data)
{
// Get the bounds.
var rows = Data[0].Count;
var cols = Data.Count;
var row = 0;
// Convert the array into a CSV string.
StringBuilder sb = new StringBuilder();
// Add the first field in this row.
sb.Append(Headers[0]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Headers[col]);
// Move to the next line.
sb.AppendLine();
for (row = 0; row < rows; row++)
{
// Add the first field in this row.
sb.Append(Data[0][row]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Data[col][row]);
// Move to the next line.
sb.AppendLine();
}
// Return the CSV format string.
return sb.ToString();
}
然后,将其导出到 Excel:
public void ExportToExcel()
{
// Initialize app and pop Excel on the screen.
var excelApp = new Excel.Application { Visible = true };
// I use unix time to give the files a unique name that's almost somewhat useful.
DateTime dateTime = DateTime.UtcNow;
long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
var path = @"C:\Users\my\path\here + unixTime + ".csv";
var csv = GetCSV();
File.WriteAllText(path, csv);
// Create a new workbook and get its active sheet.
excelApp.Workbooks.Open(path);
var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
// iterate over each value and throw it in the chart
for (var column = 0; column < Data.Count; column++)
{
((Excel.Range)workSheet.Columns[column + 1]).AutoFit();
}
currentSheet = workSheet;
}
你也必须安装一些东西......
右键单击解决方案资源管理器中的解决方案,然后选择“管理 NuGet 包”。 - 添加Microsoft.Office.Interop.Excel
如果您按照互操作希望的方式创建项目,它现在可能实际上可以工作。 如果它仍然不起作用,我必须在不同的类别中创建一个新项目。 在新建 > 项目下,选择 Visual C# > Windows 桌面 > 控制台应用程序。 否则,互操作工具将无法工作。
如果我忘记了任何事情,这是我的“使用”声明:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
你有没有听说过 NPOI,一个 .NET 库,可以在没有安装 Microsoft Office 的情况下读/写 Office 格式。 没有 COM+,没有互操作。 Github 页面
这是我的 Excel 导出类
/*
* User: TMPCSigit aswzen@gmail.com
* Date: 25/11/2019
* Time: 11:28
*
*/
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace Employee_Manager
{
public static class ExportHelper
{
public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, string value )
{
var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );
cell.SetCellValue( value );
}
public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, double value )
{
var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );
cell.SetCellValue( value );
}
public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, DateTime value )
{
var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );
cell.SetCellValue( value );
}
public static void WriteStyle( ISheet sheet, int columnIndex, int rowIndex, ICellStyle style )
{
var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );
cell.CellStyle = style;
}
public static IWorkbook CreateNewBook( string filePath )
{
IWorkbook book;
var extension = Path.GetExtension( filePath );
// HSSF => Microsoft Excel(xls形式)(excel 97-2003)
// XSSF => Office Open XML Workbook形式(xlsx形式)(excel 2007以降)
if( extension == ".xls" ) {
book = new HSSFWorkbook();
}
else if( extension == ".xlsx" ) {
book = new XSSFWorkbook();
}
else {
throw new ApplicationException( "CreateNewBook: invalid extension" );
}
return book;
}
public static void createXls(DataGridView dg){
try {
string filePath = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel XLS (*.xls)|*.xls";
sfd.FileName = "Export.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
filePath = sfd.FileName;
var book = CreateNewBook( filePath );
book.CreateSheet( "Employee" );
var sheet = book.GetSheet( "Employee" );
int columnCount = dg.ColumnCount;
string columnNames = "";
string[] output = new string[dg.RowCount + 1];
for (int i = 0; i < columnCount; i++)
{
WriteCell( sheet, i, 0, SplitCamelCase(dg.Columns[i].Name.ToString()) );
}
for (int i = 0; i < dg.RowCount; i++)
{
for (int j = 0; j < columnCount; j++)
{
var celData = dg.Rows[i].Cells[j].Value;
if(celData == "" || celData == null){
celData = "-";
}
if(celData.ToString() == "System.Drawing.Bitmap"){
celData = "Ada";
}
WriteCell( sheet, j, i+1, celData.ToString() );
}
}
var style = book.CreateCellStyle();
style.DataFormat = book.CreateDataFormat().GetFormat( "yyyy/mm/dd" );
WriteStyle( sheet, 0, 4, style );
using( var fs = new FileStream( filePath, FileMode.Create ) ) {
book.Write( fs );
}
}
}
catch( Exception ex ) {
Console.WriteLine( ex );
}
}
public static string SplitCamelCase(string input)
{
return Regex.Replace(input, "(?<=[a-z])([A-Z])", " $1", RegexOptions.Compiled);
}
}
}
我也在处理使用 C# 将数据导出到 Excel 电子表格的类似问题。 我尝试了许多使用外部 DLL 的不同方法,但没有成功。
对于导出功能,您不需要使用任何处理外部 DLL 的东西。 相反,只需维护响应的标头和内容类型。
这是一篇我觉得很有帮助的文章。 文章讨论了如何使用 ASP.NET 将数据导出到 Excel 电子表格。
http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c-sharp.html
您可以使用ExcelDataReader读取现有的Excel
文件:
using (var stream = File.Open("C:\\temp\\input.xlsx", FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read())
{
for (var i = 0; i < reader.FieldCount; i++)
{
var value = reader.GetValue(i)?.ToString();
}
}
}
}
收集所需的所有数据后,您可以尝试使用我的SwiftExcel库将其导出到新的Excel
文件中:
using (var ew = new ExcelWriter("C:\\temp\\output.xlsx"))
{
for (var i = 1; i < 10; i++)
{
ew.Write("your_data", i, 1);
}
}
安装两个库的 Nuget 命令:
安装包 ExcelDataReader
安装包 SwiftExcel
使用 .NET 的Aspose.Cells库,您可以轻松地将特定行和列的数据从一个 Excel 文档导出到另一个。 以下代码示例显示了如何使用 C# 语言执行此操作。
// Open the source excel file.
Workbook srcWorkbook = new Workbook("Source_Workbook.xlsx");
// Create the destination excel file.
Workbook destWorkbook = new Workbook();
// Get the first worksheet of the source workbook.
Worksheet srcWorksheet = srcWorkbook.Worksheets[0];
// Get the first worksheet of the destination workbook.
Worksheet desWorksheet = destWorkbook.Worksheets[0];
// Copy the second row of the source Workbook to the first row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 1, 0);
// Copy the fourth row of the source Workbook to the second row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 3, 1);
// Save the destination excel file.
destWorkbook.Save("Destination_Workbook.xlsx");
以下博客文章详细解释了如何将不同来源的数据导出到 Excel 文档。
https://blog.conholdate.com/2020/08/10/export-data-to-excel-in-csharp/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.