如何使用C#创建Excel电子表格而不需要在运行代码的计算机上安装Excel?


当前回答

您可以考虑使用XML Spreadsheet 2003格式创建文件。这是一种简单的XML格式,使用了一个文档化的模式。

其他回答

您可以使用此库创建格式良好的Excel文件:http://officehelper.codeplex.com/documentation参见以下示例:

using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
    helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
    helper.CurrentSheetName = "Sheet1";
    helper.CurrentPosition = new CellRef("C3");

    //the template xlsx should contains the named range "header"; use the command "insert"/"name".
    helper.InsertRange("header");

    //the template xlsx should contains the named range "sample1";
    //inside this range you should have cells with these values:
    //<name> , <value> and <comment>, which will be replaced by the values from the getSample()
    CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"}); 
    helper.InsertRange(sample1, getSample());

    //you could use here other named ranges to insert new cells and call InsertRange as many times you want, 
    //it will be copied one after another;
    //even you can change direction or the current cell/sheet before you insert

    //typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
    helper.DeleteSheet("Sheet3");
}        

示例如下:

private IEnumerable<List<object>> getSample()
{
    var random = new Random();

    for (int loop = 0; loop < 3000; loop++)
    {
        yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};
    }
}

我最近刚刚使用了FlexCel.NET,发现它是一个优秀的库!我对太多的软件产品不这么说。在这里进行整个销售宣传没有意义,你可以阅读他们网站上的所有功能。

这是一个商业产品,但如果你购买它,你会得到完整的源代码。所以我想,如果你真的想,你可以将它编译成你的程序集。否则,它只是一个额外的程序集来xcopy-没有配置或安装或类似的东西。

我认为,如果没有第三方库,您将找不到任何方法来做到这一点,因为.NET框架显然没有内置的支持,OLE自动化只是一个痛苦的世界。

在我的项目中,我使用一些.net库来提取Excel文件(.xls和.xlsx)

为了导出数据,我经常使用rdlc。

要修改我使用的excel文件(尝试设置空白单元格A15时的示例代码):

关闭的XML

        //Closed XML
        var workbook = new XLWorkbook(sUrlFile); // load the existing excel file
        var worksheet = workbook.Worksheets.Worksheet(1);
        worksheet.Cell("A15").SetValue("");
        workbook.Save();

铁杆XL

       string sUrlFile = "G:\\ReportAmortizedDetail.xls";
        WorkBook workbook = WorkBook.Load(sUrlFile);
        WorkSheet sheet = workbook.WorkSheets.First();
        //Select cells easily in Excel notation and return the calculated value
        sheet["A15"].First().Value = "";
        sheet["A15"].First().FormatString = "";

        workbook.Save();
        workbook.Close();
        workbook = null;

SpireXLS(当我尝试时,库会打印附加页,以提供我们使用试用库的信息

            string sUrlFile = "G:\\ReportAmortizedDetail.xls";
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(sUrlFile);
            //Get the 1st sheet
            Worksheet sheet = workbook.Worksheets[0];
            //Specify the cell range
            CellRange range = sheet.Range["A15"];
            //Find all matched text in the range
            CellRange[] cells = range.FindAllString("hi", false, false);
            //Replace text
            foreach (CellRange cell in range)
            {
                cell.Text = "";
            }
            //Save
            workbook.Save();

Jet Oledb公司

    //ExcelTool Class
    public static int ExcelUpdateSheets(string path, string sWorksheetName, string sCellLocation, string sValue)
    {
        int iResult = -99;
        String sConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO'";
        OleDbConnection objConn = new OleDbConnection(sConnectionString);
        objConn.Open();
        OleDbCommand objCmdSelect = new OleDbCommand("UPDATE [" + sWorksheetName + "$" + sCellLocation + "] SET F1=" + UtilityClass.ValueSQL(sValue), objConn);
        objCmdSelect.ExecuteNonQuery();
        objConn.Close();

        return iResult;
    }

用法:

    ExcelTool.ExcelUpdateSheets(sUrlFile, "ReportAmortizedDetail", "A15:A15", "");

天冬氨酸

            var workbook = new Aspose.Cells.Workbook(sUrlFile);
            // access first (default) worksheet
            var sheet = workbook.Worksheets[0];
            // access CellsCollection of first worksheet
            var cells = sheet.Cells;
            // write HelloWorld to cells A1
            cells["A15"].Value = "";
            // save spreadsheet to disc
            workbook.Save(sUrlFile);
            workbook.Dispose();
            workbook = null;

如果您从代码中创建数据表或数据网格视图,则可以使用此简单方法保存所有数据。不建议使用此方法,但它可以100%工作,即使您没有在计算机中安装MS Excel。

try
 {
  SaveFileDialog saveFileDialog1 = new SaveFileDialog();
  saveFileDialog1.Filter = "Excel Documents (*.xls)|*.xls";
  saveFileDialog1.FileName = "Employee Details.xls";
  if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  {
  string fname = saveFileDialog1.FileName;
  StreamWriter wr = new StreamWriter(fname);
  for (int i = 0; i <DataTable.Columns.Count; i++)
  {
  wr.Write(DataTable.Columns[i].ToString().ToUpper() + "\t");
  }
  wr.WriteLine();

  //write rows to excel file
  for (int i = 0; i < (DataTable.Rows.Count); i++)
  {
  for (int j = 0; j < DataTable.Columns.Count; j++)
  {
  if (DataTable.Rows[i][j] != null)
  {
  wr.Write(Convert.ToString(getallData.Rows[i][j]) + "\t");
  }
   else
   {
   wr.Write("\t");
   }
   }
   //go to next line
   wr.WriteLine();
   }
   //close file
   wr.Close();
   }
   }
   catch (Exception)
   {
    MessageBox.Show("Error Create Excel Sheet!");
   }

下面是使用LINQ to XML完成此操作的方法,并提供示例代码:

用LINQ to XML快速导入和导出Excel数据

它有点复杂,因为您必须导入名称空间等等,但它确实可以避免任何外部依赖。

(当然,它是VB.NET,而不是C#,但您可以始终在自己的项目中隔离VB.NET内容,以使用XML文字,并使用C#执行其他所有操作。)