如何使用C#创建Excel电子表格而不需要在运行代码的计算机上安装Excel?
当前回答
你可能想看看GemBox.Spresheet。
他们有一个免费版本,具有所有功能,但如果符合您的需要,则限制为每张150行,每张工作簿5页。
我还不需要自己使用它,但看起来很有趣。
其他回答
OpenXML也是一个很好的选择,它有助于避免在服务器上安装MS Excel。Microsoft提供的Open XML SDK 2.0简化了操作Open XML包和包中的底层Open XML架构元素的任务。开放式XML应用程序编程接口(API)封装了开发人员在开放式XML包上执行的许多常见任务。
看看OpenXML:有助于避免在服务器上安装MS Excel的替代方案
商业解决方案SpreadsheetGearfor.NET将做到这一点。
您可以在此处查看ASP.NET(C#和VB)的实时示例,并在此处下载评估版本。
免责声明:我拥有SpreadsheetGear LLC
我编写了一个简单的代码,通过使用System.IO.StreamWriter将数据集导出到excel,而不使用excel对象。
下面是代码,它将从数据集中读取所有表,并将它们逐一写入工作表。我从这篇文章中得到了帮助。
public static void exportToExcel(DataSet source, string fileName)
{
const string endExcelXML = "</Workbook>";
const string startExcelXML = "<xml version>\r\n<Workbook " +
"xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
"xmlns:x=\"urn:schemas- microsoft-com:office:" +
"excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
"office:spreadsheet\">\r\n <Styles>\r\n " +
"<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
"<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
"\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
"\r\n <Protection/>\r\n </Style>\r\n " +
"<Style ss:ID=\"BoldColumn\">\r\n <Font " +
"x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
" ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"Decimal\">\r\n <NumberFormat " +
"ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
"ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
"ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
"</Styles>\r\n ";
System.IO.StreamWriter excelDoc = null;
excelDoc = new System.IO.StreamWriter(fileName);
int sheetCount = 1;
excelDoc.Write(startExcelXML);
foreach (DataTable table in source.Tables)
{
int rowCount = 0;
excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
excelDoc.Write("<Table>");
excelDoc.Write("<Row>");
for (int x = 0; x < table.Columns.Count; x++)
{
excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
excelDoc.Write(table.Columns[x].ColumnName);
excelDoc.Write("</Data></Cell>");
}
excelDoc.Write("</Row>");
foreach (DataRow x in table.Rows)
{
rowCount++;
//if the number of rows is > 64000 create a new page to continue output
if (rowCount == 64000)
{
rowCount = 0;
sheetCount++;
excelDoc.Write("</Table>");
excelDoc.Write(" </Worksheet>");
excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
excelDoc.Write("<Table>");
}
excelDoc.Write("<Row>"); //ID=" + rowCount + "
for (int y = 0; y < table.Columns.Count; y++)
{
System.Type rowType;
rowType = x[y].GetType();
switch (rowType.ToString())
{
case "System.String":
string XMLstring = x[y].ToString();
XMLstring = XMLstring.Trim();
XMLstring = XMLstring.Replace("&", "&");
XMLstring = XMLstring.Replace(">", ">");
XMLstring = XMLstring.Replace("<", "<");
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write(XMLstring);
excelDoc.Write("</Data></Cell>");
break;
case "System.DateTime":
//Excel has a specific Date Format of YYYY-MM-DD followed by
//the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
//The Following Code puts the date stored in XMLDate
//to the format above
DateTime XMLDate = (DateTime)x[y];
string XMLDatetoString = ""; //Excel Converted Date
XMLDatetoString = XMLDate.Year.ToString() +
"-" +
(XMLDate.Month < 10 ? "0" +
XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
"-" +
(XMLDate.Day < 10 ? "0" +
XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
"T" +
(XMLDate.Hour < 10 ? "0" +
XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
":" +
(XMLDate.Minute < 10 ? "0" +
XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
":" +
(XMLDate.Second < 10 ? "0" +
XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
".000";
excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
"<Data ss:Type=\"DateTime\">");
excelDoc.Write(XMLDatetoString);
excelDoc.Write("</Data></Cell>");
break;
case "System.Boolean":
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.Byte":
excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
"<Data ss:Type=\"Number\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.Decimal":
case "System.Double":
excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
"<Data ss:Type=\"Number\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.DBNull":
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write("");
excelDoc.Write("</Data></Cell>");
break;
default:
throw (new Exception(rowType.ToString() + " not handled."));
}
}
excelDoc.Write("</Row>");
}
excelDoc.Write("</Table>");
excelDoc.Write(" </Worksheet>");
sheetCount++;
}
excelDoc.Write(endExcelXML);
excelDoc.Close();
}
在我的项目中,我使用一些.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;
前段时间,我在NPOI上创建了一个DLL。使用它非常简单:
IList<DummyPerson> dummyPeople = new List<DummyPerson>();
//Add data to dummyPeople...
IExportEngine engine = new ExcelExportEngine();
engine.AddData(dummyPeople);
MemoryStream memory = engine.Export();
你可以在这里阅读更多。
顺便说一句,它是100%开源的。随时使用、编辑和共享;)
推荐文章
- .NET中的Map和Reduce
- 我如何能使一个组合框不可编辑的。net ?
- .NET反射的成本有多高?
- 实体框架回滚并移除不良迁移
- 将流转换为字符串并返回
- 在c#中检查字符串是否只包含数字的最快方法
- IEquatable和重写Object.Equals()之间的区别是什么?
- 创建一个堆栈大小为默认值50倍的线程有什么危险?
- 转换JSON字符串到JSON对象c#
- .text, .value和.value2之间的区别是什么?
- 显示两个datetime值之间的小时差值
- 如何设置enum为空
- 选择Enum类型的默认值而无需更改值
- 我如何设置在一个组合框中选择的项目,以匹配我的字符串使用c# ?
- String与StringBuilder