- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 OpenXml 生成 Excel 文件,在研究了大量不同的示例代码和 SDK Productivity Tool 后,终于得到了我想要的东西。只有一件事我无法回避。当我使用 Excel 打开文件并尝试将单元格复制/粘贴到另一个 Excel 文件时,我收到“该命令无法用于多项选择”。这绝对不是一个非相邻选择问题,因为即使只有一个单元格我也无法做到这一点。此外,如果我用 Excel 保存文件并重新打开它,问题就会消失,所以我认为这可能与我创建文件的方式有关。任何建议,将不胜感激。这是我用来生成文件的代码:
public class ExcelGenerator
{
#region Fields
private List<Tuple<DbDataReader, string>> datasource;
private string[] cellReferences = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
private SpreadsheetDocument workbook;
Hashtable stringItemIndexMap;
int nextIndex;
private uint numberStyleID;
private uint decimalStyleID;
private uint textStyleID;
private uint headerTextStyleID;
#endregion
#region Constructors
public ExcelGenerator(DbDataReader reader, string sheetName) : this(new List<Tuple<DbDataReader, string>>() { new Tuple<DbDataReader, string>(reader, sheetName) }) { }
public ExcelGenerator(List<Tuple<DbDataReader, string>> datasource)
{
if (datasource == null)
{
throw new Exception("The value of 'datasource' cannot be null.");
}
this.datasource = datasource;
this.stringItemIndexMap = new Hashtable();
cellReferences = cellReferences.Concat(cellReferences.SelectMany(a => cellReferences.Select(b => a + b))).ToArray();
}
#endregion
#region Properties
public Dictionary<string, string> FieldTitleMappings { get; set; }
public string[] FieldsToExport { get; set; }
#endregion
#region Methods
public void Generate(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
using (workbook = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook))
{
Generate(workbook);
}
}
public void Generate(Stream workBookStream)
{
if (workBookStream == null)
{
throw new ArgumentNullException("workBookStream");
}
using (workbook = SpreadsheetDocument.Create(workBookStream, SpreadsheetDocumentType.Workbook))
{
Generate(workbook);
}
}
public void Generate(SpreadsheetDocument workbook)
{
if (workbook == null)
{
throw new ArgumentNullException("workbook");
}
workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new Workbook();
workbook.WorkbookPart.AddNewPart<SharedStringTablePart>();
var worksheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheets = workbook.WorkbookPart.Workbook.AppendChild(new Sheets());
workbook.WorkbookPart.AddNewPart<WorkbookStylesPart>();
workbook.WorkbookPart.WorkbookStylesPart.Stylesheet = CreateStylesheet();
workbook.WorkbookPart.WorkbookStylesPart.Stylesheet.Save();
uint sheetCounter = 0;
foreach (var ds in datasource)
{
var reader = ds.Item1;
Worksheet worksheet = new Worksheet();
SheetData sheetData = new SheetData();
SheetViews sheetViews = new SheetViews();
SheetView sheetView = new SheetView() { RightToLeft = true, TabSelected = true, WorkbookViewId = (UInt32Value)0U };
Selection selection = new Selection() { ActiveCell = "A1", SequenceOfReferences = new ListValue<StringValue>() { InnerText = "A1" } };
sheetView.Append(selection);
sheetViews.Append(sheetView);
worksheet.Append(sheetViews);
#region Generate header
uint counter = 0;
var headerRow = new Row();
headerRow.RowIndex = ++counter;
var schema = reader.GetSchemaTable();
var dataTypes = new List<Type>();
var columnHeaders = new List<string>();
foreach (DataRow r in schema.Rows)
{
var c = new Cell();
var headerText = r["ColumnName"].ToString();
if (FieldTitleMappings != null && FieldTitleMappings.ContainsKey(headerText))
{
headerText = FieldTitleMappings[headerText];
}
c.DataType = CellValues.String;
c.CellValue = new CellValue(headerText);
c.StyleIndex = headerTextStyleID;
headerRow.AppendChild(c);
dataTypes.Add((Type)r["DataType"]);
columnHeaders.Add(headerText);
}
CreateColumnsFromHeaderText(worksheet, columnHeaders);
sheetData.AppendChild(headerRow);
#endregion
#region Populate contents
var fieldsCount = reader.FieldCount;
while (reader.Read())
{
object[] currentRowData = new object[fieldsCount];
reader.GetValues(currentRowData);
var row = new Row();
row.RowIndex = ++counter;
for (var i = 0; i < fieldsCount; i++)
{
row.AppendChild(CreateCell(currentRowData[i], dataTypes[i], cellReferences[i] + row.RowIndex));
}
sheetData.AppendChild(row);
}
#endregion
workbook.WorkbookPart.SharedStringTablePart.SharedStringTable.Save();
worksheet.AppendChild(sheetData);
worksheetPart.Worksheet = worksheet;
worksheetPart.Worksheet.Save();
sheets.AppendChild(new Sheet()
{
Id = workbook.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = ++sheetCounter,
Name = ds.Item2
});
}
workbook.WorkbookPart.Workbook.Save();
}
private Stylesheet CreateStylesheet()
{
Stylesheet ss = new Stylesheet();
Fonts fts = new Fonts();
Font ft = new Font();
FontName ftn = new FontName();
ftn.Val = "Tahoma";
FontSize ftsz = new FontSize();
ftsz.Val = 10;
ft.FontName = ftn;
ft.FontSize = ftsz;
fts.Append(ft);
ft = new Font();
ftn = new FontName();
ftn.Val = "Tahoma";
ftsz = new FontSize();
ftsz.Val = 10;
ft.FontName = ftn;
ft.FontSize = ftsz;
ft.Bold = new Bold { Val = true };
fts.Append(ft);
fts.Count = (uint)fts.ChildElements.Count;
Fills fills = new Fills() { Count = (UInt32Value)3U };
Fill fill1 = new Fill();
PatternFill patternFill1 = new PatternFill() { PatternType = PatternValues.None };
fill1.Append(patternFill1);
Fill fill2 = new Fill();
PatternFill patternFill2 = new PatternFill() { PatternType = PatternValues.Gray125 };
fill2.Append(patternFill2);
Fill fill3 = new Fill();
PatternFill patternFill3 = new PatternFill() { PatternType = PatternValues.Solid };
ForegroundColor foregroundColor1 = new ForegroundColor() { Theme = (UInt32Value)0U, Tint = -0.14999847407452621D };
BackgroundColor backgroundColor1 = new BackgroundColor() { Indexed = (UInt32Value)64U };
patternFill3.Append(foregroundColor1);
patternFill3.Append(backgroundColor1);
fill3.Append(patternFill3);
fills.Append(fill1);
fills.Append(fill2);
fills.Append(fill3);
Borders borders = new Borders() { Count = (UInt32Value)2U };
Border border1 = new Border();
LeftBorder leftBorder1 = new LeftBorder();
RightBorder rightBorder1 = new RightBorder();
TopBorder topBorder1 = new TopBorder();
BottomBorder bottomBorder1 = new BottomBorder();
DiagonalBorder diagonalBorder1 = new DiagonalBorder();
border1.Append(leftBorder1);
border1.Append(rightBorder1);
border1.Append(topBorder1);
border1.Append(bottomBorder1);
border1.Append(diagonalBorder1);
Border border2 = new Border();
LeftBorder leftBorder2 = new LeftBorder() { Style = BorderStyleValues.Thin };
Color color2 = new Color() { Indexed = (UInt32Value)64U };
leftBorder2.Append(color2);
RightBorder rightBorder2 = new RightBorder() { Style = BorderStyleValues.Thin };
Color color3 = new Color() { Indexed = (UInt32Value)64U };
rightBorder2.Append(color3);
TopBorder topBorder2 = new TopBorder() { Style = BorderStyleValues.Thin };
Color color4 = new Color() { Indexed = (UInt32Value)64U };
topBorder2.Append(color4);
BottomBorder bottomBorder2 = new BottomBorder() { Style = BorderStyleValues.Thin };
Color color5 = new Color() { Indexed = (UInt32Value)64U };
bottomBorder2.Append(color5);
DiagonalBorder diagonalBorder2 = new DiagonalBorder();
border2.Append(leftBorder2);
border2.Append(rightBorder2);
border2.Append(topBorder2);
border2.Append(bottomBorder2);
border2.Append(diagonalBorder2);
borders.Append(border1);
borders.Append(border2);
CellStyleFormats csfs = new CellStyleFormats();
CellFormat cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 0;
cf.Alignment = new Alignment { Horizontal = HorizontalAlignmentValues.Right };
csfs.Append(cf);
csfs.Count = (uint)csfs.ChildElements.Count;
uint iExcelIndex = 164;
NumberingFormats nfs = new NumberingFormats();
CellFormats cfs = new CellFormats();
cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 0;
cf.FormatId = 0;
cf.Alignment = new Alignment { Horizontal = HorizontalAlignmentValues.Right };
cfs.Append(cf);
cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.Alignment = new Alignment { Horizontal = HorizontalAlignmentValues.Right };
cfs.Append(cf);
textStyleID = (uint)(cfs.ChildElements.Count - 1);
NumberingFormat nf;
nf = new NumberingFormat();
nf.NumberFormatId = iExcelIndex++;
nf.FormatCode = "dd/mm/yyyy hh:mm:ss";
nfs.Append(nf);
cf = new CellFormat();
cf.NumberFormatId = nf.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = true;
cf.Alignment = new Alignment { Horizontal = HorizontalAlignmentValues.Right };
cfs.Append(cf);
nf = new NumberingFormat();
nf.NumberFormatId = iExcelIndex++;
nf.FormatCode = "#,##0";
nfs.Append(nf);
cf = new CellFormat();
cf.NumberFormatId = nf.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = true;
cf.Alignment = new Alignment { Horizontal = HorizontalAlignmentValues.Right };
cfs.Append(cf);
decimalStyleID = (uint)(cfs.ChildElements.Count - 1);
// #,##0.00 is also Excel style index 4
nf = new NumberingFormat();
nf.NumberFormatId = iExcelIndex++;
nf.FormatCode = "#";
nfs.Append(nf);
cf = new CellFormat();
cf.NumberFormatId = nf.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = true;
cf.Alignment = new Alignment { Horizontal = HorizontalAlignmentValues.Right };
cfs.Append(cf);
numberStyleID = (uint)(cfs.ChildElements.Count - 1);
cf = new CellFormat();
cf.FontId = 1;
cf.FillId = 2;
cf.BorderId = 1;
cf.FormatId = 0;
cf.Alignment = new Alignment { Horizontal = HorizontalAlignmentValues.Right };
cf.ApplyNumberFormat = true;
cfs.Append(cf);
headerTextStyleID = (uint)(cfs.ChildElements.Count - 1);
nfs.Count = (uint)nfs.ChildElements.Count;
cfs.Count = (uint)cfs.ChildElements.Count;
ss.Append(nfs);
ss.Append(fts);
ss.Append(fills);
ss.Append(borders);
ss.Append(csfs);
ss.Append(cfs);
CellStyles css = new CellStyles();
CellStyle cs = new CellStyle();
cs.Name = "Normal";
cs.FormatId = 0;
cs.BuiltinId = 0;
css.Append(cs);
css.Count = (uint)css.ChildElements.Count;
ss.Append(css);
DifferentialFormats dfs = new DifferentialFormats();
dfs.Count = 0;
ss.Append(dfs);
TableStyles tss = new TableStyles();
tss.Count = 0;
tss.DefaultTableStyle = "TableStyleMedium9";
tss.DefaultPivotStyle = "PivotStyleLight16";
ss.Append(tss);
return ss;
}
private ForegroundColor TranslateForeground(System.Drawing.Color fillColor)
{
return new ForegroundColor()
{
Rgb = new HexBinaryValue()
{
Value =
System.Drawing.ColorTranslator.ToHtml(
System.Drawing.Color.FromArgb(
fillColor.A,
fillColor.R,
fillColor.G,
fillColor.B)).Replace("#", "")
}
};
}
private Cell CreateCell(object value, Type dataType, string cellReference)
{
var cell = new Cell();
cell.CellReference = cellReference;
value = value ?? "";
if (dataType == typeof(decimal))
{
cell.DataType = CellValues.Number;
cell.CellValue = new CellValue(value.ToString());
cell.StyleIndex = decimalStyleID;
}
else if (dataType == typeof(int) || dataType == typeof(short) || dataType == typeof(long) ||
dataType == typeof(uint) || dataType == typeof(ushort) || dataType == typeof(ulong))
{
cell.DataType = CellValues.Number;
cell.CellValue = new CellValue(value.ToString());
cell.StyleIndex = numberStyleID;
}
else
{
if (value is DateTime)
{
value = DateTimeUtil.ToShamsiDate((DateTime)value);
}
cell.DataType = CellValues.SharedString;
cell.CellValue = new CellValue(InsertSharedStringItem(value.ToString()));
cell.StyleIndex = textStyleID;
}
return cell;
}
private string InsertSharedStringItem(string value)
{
if (workbook.WorkbookPart.SharedStringTablePart.SharedStringTable == null)
{
workbook.WorkbookPart.SharedStringTablePart.SharedStringTable = new SharedStringTable();
nextIndex = 0;
}
var i = 0;
var index = stringItemIndexMap[value] as string;
if (index == null)
{
workbook.WorkbookPart.SharedStringTablePart.SharedStringTable.AppendChild(new SharedStringItem(new Text(value)));
index = nextIndex.ToString();
stringItemIndexMap.Add(value, index);
nextIndex++;
}
return index;
}
public void CreateColumnsFromHeaderText(Worksheet workSheet, IEnumerable<string> headerTexts)
{
Columns columns = new Columns();
uint index = 1;
foreach (var sILT in headerTexts)
{
double fSimpleWidth = 0.0f;
double fWidthOfZero = 0.0f;
double fDigitWidth = 0.0f;
double fMaxDigitWidth = 0.0f;
double fTruncWidth = 0.0f;
System.Drawing.Font drawfont = new System.Drawing.Font("Tahoma", 10);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(new System.Drawing.Bitmap(200, 200));
fWidthOfZero = (double)g.MeasureString("0", drawfont).Width;
fSimpleWidth = (double)g.MeasureString(sILT, drawfont).Width;
fSimpleWidth = fSimpleWidth / fWidthOfZero;
for (int i = 0; i < 10; ++i)
{
fDigitWidth = (double)g.MeasureString(i.ToString(), drawfont).Width;
if (fDigitWidth > fMaxDigitWidth)
{
fMaxDigitWidth = fDigitWidth;
}
}
g.Dispose();
// Truncate([{Number of Characters} * {Maximum Digit Width} + {5 pixel padding}] / {Maximum Digit Width} * 256) / 256
fTruncWidth = Math.Truncate((sILT.ToCharArray().Count() * fMaxDigitWidth + 40.0) / fMaxDigitWidth * 256.0) / 256.0;
var column = new Column();
column.Min = index;
column.Max = index++;
column.Width = fTruncWidth;
column.CustomWidth = true;
columns.Append(column);
}
workSheet.Append(columns);
}
#endregion
}
最佳答案
我遇到了这个问题,发现这是由于未将 BookViews 对象附加到工作簿而导致的。 BookViews 必须附加在 Sheets 对象之前:
workbook.Append(new BookViews(new WorkbookView()));
关于openxml - 使用 OpenXml 创建 Excel 文件后复制/粘贴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9464439/
我的 C# 应用程序使用 OpenXML 创建一个 MSWord 文档,其中已经包含多个表。最后一部分是添加条形图。我找不到这个案例的好例子。 谢谢你的帮助! 我正在从头开始创建文档。从...开始:
我正在使用一个模板文档,该文档使用 CustomXmlBlocks 作为占位符来放置表格和其他信息。我需要能够以某种方式将图像放入其中一个 block 中......即使它首先放入运行中。 图像以字节
我正在以编程方式将 OpenXML 段落添加到 Word 文档中,并且稍后我需要能够将该段落识别为我的段落。关于如何做到这一点有什么想法吗?我尝试插入 XML 注释和扩展属性,但是当您将文档保存在 w
我想使用 openxml 删除一列,我能够清除单元格的内容,但一直无法找到删除列的文档,以便在删除列时向左移动其他单元格。如何使用 openxml 删除列,它将单元格向左移动? 最佳答案 我发现 Op
我找不到任何可以告诉我 txBody 标签中的文本是否带有项目符号的指标,您能否请我确定我应该使用哪个指标来了解文本是项目符号还是普通文本? -谢谢 最佳答案 在 txBody 标签内,您可以查找标签
我目前正在尝试使用 PHPWord 库及其模板系统来处理 docx 文件。我已经找到并更新了这个库的某人(不记得名字,但它并不重要)的路径,该库可以使用表(复制其行,然后在每一行上使用 PHPWord
这个问题已经有答案了: 已关闭11 年前。 Possible Duplicate: Open Xml and Date format in Excel cell 我正在尝试从 DataGridView
我发现各种元素非常困惑。几乎每个元素似乎都有一个与之关联的“部分”,我不确定它们是如何粘合在一起的。 工作簿工作簿部分工作表工作表部分 我也对 DocumentFormat.OpenXml.Packa
我有一个存储在 Bitmap 对象中的图像,我想将其粘贴到 OpenXML 文档中。我尝试使用 MemoryStream 作为中间步骤,如下所示: ImagePart part = container
我试图理解 OpenXML 电子表格的内部文件内容。在一些文件中,我发现了这个字符串。其他标签具有相同的前缀。标签也可以有前缀 p: w: 等。 你能帮我理解这些前缀在标签中的含义吗? 最佳答案 您可
我的预期结果是: 你好 世界! 但是当我使用以下代码时: MainDocumentPart mainDocumentPart = package.AddMainDo
我需要将多个 .docx 文件收集到一个文件夹中,并将它们“链接”成一个将显示给用户的文档。 现在我已经阅读了 Brian Jones' article虽然听起来很有希望,但我遇到了一个问题。 当我使
我正在使用 OpenXml 生成 Excel 文件,在研究了大量不同的示例代码和 SDK Productivity Tool 后,终于得到了我想要的东西。只有一件事我无法回避。当我使用 Excel 打
我正在使用 openxml 创建 WordProcessingDocuments(工作正常,生成的 word 文档正是我想要的),现在我正在尝试使用 openxml Powertools 将这些新创建
我使用 OpenXML SDK 2.5 编写了一个 Word 文档,当我在 MS Office 中预览该文档时,该文档给出了预期的外观和格式。 现在我需要将此文档转换为 HTML 文档,我开始了解 O
我是 .net 编码员,我对 ColdFusion 真的很陌生。我编写了一个自动生成发票的 .dll 库。我需要使用 ColdFusion 应用程序中的库。我已经成功地将我的库中的类加载为 coldf
以前我发布了一个问题,如何将数据集中的数据填充到 excel 工作表中,而不是如何使用该数据创建图表。那篇文章不太走运,但现在我设法从数据集中填充数据,但也在努力根据该数据创建图表,我希望图表与我的数
快要被这个问题搞疯了。我确信它是如此简单,我只是错过了它,但我一生都无法找出如何使用 C# 中的 OpenXml SDK v2.0 更改 Word 2007 中的内容控件的内容。 我创建了一个带有纯文
我正在编写一个小应用程序,它将路径作为输入,然后获取该路径中的每个 docx 文件,用关键字替换每个超链接。 奇怪的是,我发现了两种超链接,第一种来自 WordprocessingDocument E
我有一段文字想在文档的中央出现。如何在docx4j中执行此操作?我目前正在使用: PPr paragraphProperties = factory.createPPr(); //cr
我是一名优秀的程序员,十分优秀!